本文介绍了转换HH:mm:ss以秒为单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本从yyyy-MM-dd HH:mm:ss日期格式中提取HH:mm:ss

I am using the following script to extract HH:mm:ss from a yyyy-MM-dd HH:mm:ss date format

import java.sql.Time

case class Transactions(creationTime: Time)

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

def parseTransac(line: String): (Transactions) = {
   val fields = line.split(',')
   val creationTime = new Time(formatter.parse(fields(0)).getTime())
   val transactions = Transactions(creationTime)
   (transactions)
}

因此,例如 2009-01-15 15:45:23 将返回 15:45:23 .

如何以秒为单位(56723)而不是HH:mm:ss

How can I obtain the result in seconds (56723) instead of HH:mm:ss

推荐答案

根据Jesper的建议,以下是解决方法:

Based on Jesper's suggestion, here is the solution :

import java.sql.Time

case class Transactions(creationSeconds: Int )

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

def parseTransac(line: String): (Transactions) = {
   val fields = line.split(',')
   val fullDateTime = new Time(formatter.parse(fields(0)).getTime())
   val creationTime = fullDateTime.toString.split(':')
   val creationSeconds = creationTime(0).toInt*3600 + creationTime(1).toInt*60 + creationTime(2).toInt
   val transactions = Transactions(creationSeconds)
   (transactions)
}

这是基于Dipankar提示的另一种解决方案:

and here is another solution based on Dipankar's hint:

import java.sql.Time
import org.joda.time.DateTime

case class Transactions(creationTime: Int)

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

def parseTransac(line: String): (Transactions) = {
   val fields = line.split(',')
   val fullDatTime = new DateTime(formatter.parse(fields(0)).getTime())
   val fromMidnight = fullDatTime.withTimeAtStartOfDay()
   val duration = new Duration(fromMidnight, fullDatTime)
   val creationTime = duration.toStandardSeconds().getSeconds()
   val transactions = Transactions(creationTime)
   (transactions)
}

这篇关于转换HH:mm:ss以秒为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:02