如何在java中将UTC日期格式字符串转换为日期格式?
我有一个要求,其中日期是UTC格式,如: Thu Jan 1 19:30:00 UTC + 0530 1970 。 我想转换为正常的日期格式dd-MM-yyyy HH:mm:ss .Below是我试过的代码。
DateFormat formatter = new SimpleDateFormat("E,MMM dd,yyyy h:mmaa"); String today = formatter.format("Thu Jan 1 19:30:00 UTC+0530 1970"); SimpleDateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); Date d = f.parse(masterDetailsJsonObject.get("cols1").toString());
但它引发了一个例外,称无法解析日期。 请指导。 提前致谢。
你可以试试这个
java.util.Date dt = new java.util.Date("Thu Jan 1 19:30:00 UTC+0530 1970"); String newDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(dt); System.out.println(""+newDateFormat);
乔达时间
使用第三方开源日期时间库Joda-Time ,这种工作要容易得多。
请注意,与java.util.Date不同,Joda-Time DateTime知道自己的时区。
以下是使用Joda-Time 2.3的一些示例代码。
String input = "Thu Jan 1 19:30:00 UTC+0530 1970"; DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss 'UTC'Z yyyy" ); // Adding "withOffsetParsed()" means "set new DateTime's time zone offset to match input string". DateTime dateTime = formatter.withOffsetParsed().parseDateTime( input ); // Convert to UTC/GMT (no time zone offset). DateTime dateTimeUtc = dateTime.toDateTime( DateTimeZone.UTC ); // Convert to India time zone. That is +05:30 (notice half-hour difference). DateTime dateTimeIndia = dateTimeUtc.toDateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
转储到控制台……
System.out.println( "dateTime: " + dateTime ); System.out.println( "dateTimeUtc: " + dateTimeUtc ); System.out.println( "dateTimeIndia: " + dateTimeIndia );
跑的时候……
dateTime: 1970-01-01T19:30:00.000+05:30 dateTimeUtc: 1970-01-01T14:00:00.000Z dateTimeIndia: 1970-01-01T19:30:00.000+05:30
回到过去
如果您需要java.util.Date用于其他目的,请转换DateTime。
java.util.Date date = dateTime.toDate();
格式化字符串
要将DateTime表示为特定格式的新String,请在StackOverflow中搜索“joda format”。 你会发现很多问题和答案。
Joda-Time提供了许多用于生成字符串的function,包括用于ISO 8601格式的默认格式化程序(如上所示),区域设置敏感格式,可自动更改元素的顺序,甚至将单词翻译成各种语言,从用户计算机设置中感知的格式。 如果这些都不能满足您的特殊需求,您可以在Joda-Time的帮助下定义自己的格式。
Locale.setDefault(Locale.US); SimpleDateFormat sourceDateFormat = new SimpleDateFormat("E MMM d HH:mm:ss 'UTC'Z yyyy"); Date sourceDate = sourceDateFormat.parse("Thu Jan 1 19:30:00 UTC+0530 1970"); System.out.println(sourceDate); SimpleDateFormat targetFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String targetString = targetFormat.format(sourceDate); System.out.println(targetString);
使用“ E MMM d HH:mm:ss 'UTC'Z yyyy
”作为源格式。 我不喜欢Java的Date API,特别是对于TimeZone
案例。 Joda-Time似乎很好。