Timestamp convert [duplicate]

此生再无相见时 提交于 2020-01-30 13:02:12

问题


My below function doesn't cast the date to the defined format.

  val oldFormat= new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS")
  val newFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS",Locale.ENGLISH)
  newFormat.format(oldFormat.parse(s).getTime))

Input date is in format yyyy-MM-dd-HH.mm.ss.SSSSSS, need to convert that into yyyy-MM-dd hh:mm:ss.SSSSSS.

my input is 2019-10-08-03.57.14.694695 but the above code outputs to 2019-10-08 04:15:04.000695 what am I doing wrong here


回答1:


Using the newer DatetimeFormatter and LocalDateTime API introduced in Java 8:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*


fun main(args: Array<String>){

    val oldFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS")
    val localDateTime = LocalDateTime.parse("2019-10-08-03.57.14.694695", oldFormatter)
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS", Locale.ENGLISH)
    val output = formatter.format(localDateTime)
    println(output)

}

I created a custom formatter and obtained date object which I reformatted again using a different custom formatter.




回答2:


https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html. S - its milliseconds, which means max value its 999. If you write S more than 3 times its just adds leading zeros.

But you can use java.time where S its second part:

    final String input = "2019-10-08-03.57.14.694695";
    final TemporalAccessor ta = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS").parse(input);
    final DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss.SSSSSS", Locale.ENGLISH);
    final String result = newFormatter.format(ta);



回答3:


Using Java 8

String InputFormat = "yyyy-MM-dd-HH.mm.ss.SSSSSS";
String outputFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS";

String input = "2019-10-08-03.57.14.694695";

LocalDateTime ldt = LocalDateTime.parse(input, DateTimeFormatter.ofPattern(InputFormat));

String result = DateTimeFormatter.ofPattern(outputFormat).format(ldt);
System.out.println(result);

If you still want to use SimpleDateFormat, the work around is as follows using @tutejszy answer

String input = "2019-10-08-03.57.14.694695";

String microseconds = input.substring(input.lastIndexOf('.')+1);
int ms= Integer.parseInt(microseconds);

input= input.substring(0,input.lastIndexOf('.')+1) + "000000";

SimpleDateFormat in = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS");

String result = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss.").format(in.parse(input))
+ String.format("%06d", ms%1000000);

System.out.println(result);


来源:https://stackoverflow.com/questions/58705924/timestamp-convert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!