Java简单日期格式化程序显示错误的值

huangapple go评论73阅读模式
英文:

Java Simple Date formatter displaying wrong value

问题

遇到了使用 SimpleDateFormat 显示纳秒的问题。

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");
Date dt = sdf.parse("03.08.2020 05:35:19:7600000");
System.out.println("Date  :" + sdf.format(dt));

输出为:Date :03.08.2020 07:41:59:0000000.

您是否可以帮助将输出中的纳秒显示为:7600000?谢谢!

英文:

Having issue displaying nano seconds using SimpleDateFormat.

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");		
Date dt = sdf.parse("03.08.2020 05:35:19:7600000");	
System.out.println("Date  :" + sdf.format(dt) );

Output is: Date :03.08.2020 07:41:59:0000000.

Can you please help make the output show nano seconds as: 7600000? Thanks!

答案1

得分: 2

建议您从过时且容易出错的传统日期时间API切换到现代日期时间API

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss:SSSSSSS");
        LocalDateTime ldt = LocalDateTime.parse("03.08.2020 05:35:19:7600000", format);
        System.out.println(ldt);
    }
}

输出:

2020-08-03T05:35:19.760
英文:

I suggest you switch from the outdated and error-prone legacy date-time API to the modern date-time API.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
	public static void main(String[] args) {
		DateTimeFormatter format = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss:SSSSSSS");
		LocalDateTime ldt = LocalDateTime.parse("03.08.2020 05:35:19:7600000", format);
		System.out.println(ldt);
	}
}

Output:

2020-08-03T05:35:19.760

答案2

得分: 0

你可以尝试以下方法,然后解析所需的日期:

sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta");

英文:

You can also try the following and then parse the required date :

sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta");

huangapple
  • 本文由 发表于 2020年8月4日 03:20:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63235660.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定