我需要编写一个函数来将任何日期时间字符串转换为EpochMillisecond,并且我已经编写了以下内容
val dateMatch1:Regex = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
val timeMatch1:Regex = """(\d\d):(\d\d):(\d\d).(\d\d\d)""".r
val timeMatch2:Regex = """(\d\d):(\d\d):(\d\d)""".r
val timeMatch3:Regex = """(\d\d):(\d\d)""".r
val timeMatch4:Regex = """(\d\d)""".r
val dateTimeMatch1:Regex = """(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d).(\d\d\d)""".r
val dateTimeMatch2:Regex = """(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)""".r
val dateTimeMatch3:Regex = """(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d)""".r
val dateTimeMatch4:Regex = """(\d\d\d\d)-(\d\d)-(\d\d) (\d\d)""".r
def stringToTime(data:String): Long = {
val now = LocalDateTime.now()
LocalDate.of(now.getYear, now.getMonthValue, now.getDayOfMonth)
val (year:Int, month:Int, day:Int, hour:Int, minute:Int, second:Int,nanoSecond:Int) = data match {
case dateMatch1(year, month, day) => (year.toInt, month.toInt, day.toInt, 0, 0, 0, 0)
case timeMatch1(hour, minute, second,nanoSecond) => (now.getYear, now.getMonthValue, now.getDayOfMonth,hour.toInt, minute.toInt, second.toInt, nanoSecond.toInt * Math.pow(10,6).toInt)
case timeMatch2(hour, minute, second) =>(now.getYear, now.getMonthValue, now.getDayOfMonth,hour.toInt,hour.toInt, minute.toInt, second.toInt,0)
case timeMatch3(hour, minute) => (now.getYear, now.getMonthValue, now.getDayOfMonth,hour.toInt,hour.toInt, minute.toInt,0,0)
case timeMatch4(hour) => (now.getYear, now.getMonthValue, now.getDayOfMonth,hour.toInt,hour.toInt, 0,0,0)
case dateTimeMatch1(year, month, day, hour, minute, second,nanoSecond) =>(year.toInt, month.toInt, day.toInt, hour.toInt, minute.toInt, second.toInt, nanoSecond.toInt * Math.pow(10,6).toInt)
case dateTimeMatch2(year, month, day, hour, minute, second) => (year.toInt, month.toInt, day.toInt, hour.toInt, minute.toInt, second.toInt,0)
case dateTimeMatch3(year, month, day, hour, minute) => (year.toInt, month.toInt, day.toInt, hour.toInt, minute.toInt,0,0)
case dateTimeMatch4(year, month, day, hour) => (year.toInt, month.toInt, day.toInt, hour.toInt,0,0,0 )
case _ => (now.getYear,now.getMonthValue,now.getDayOfMonth,0,0,0,0)
}
LocalDateTime.of(year, month, day, hour, minute, second,nanoSecond).atZone(ZoneId.systemDefault()).toInstant.toEpochMilli
}
这很好但我正在寻找更好的方法。有人请帮助我