gpt4 book ai didi

java - 时区转换期间的奇怪行为

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:41 26 4
gpt4 key购买 nike

我正在尝试将以 EST 时区打印的日期转换为以 GMT/UTC 打印的日期

package com.stefano;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class MainEntry {

/**
* @param args
* @throws ParseException
*/


public static void main(String[] args) throws ParseException {


String dateTime = "1307011200"; //12:00PM 01 July 2013
System.out.println("Input -> " + dateTime);
SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmm");
format.setTimeZone(TimeZone.getTimeZone("EST"));
Date date = format.parse(dateTime);
System.out.println("Intermediate -> " + date);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Output -> " + format.format(date));


}

}

它给出的输出是:

Input -> 1307011200
Intermediate -> Mon Jul 01 17:00:00 BST 2013
Output -> 1307011600

尽管 EST 和 GMT 之间的时差始终为 5,但不知何故与 BST 有所牵连。

我不能使用 Joda-Time .

最佳答案

SimpleDateFormat.parse(String) 方法的 javadoc 引用了 parse(String, ParsePosition) 方法,它说:

This parsing operation uses the calendar to produce a Date. As a result, the calendar's date-time fields and the TimeZone value may have been overwritten, depending on subclass implementations. Any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations.

据此,您不能使用此方法来告诉 SimpleDateFormat 哪个时区给定的日期是在。您可以像这样修复此方法:

String dateTime = "1307011200"; // 12:00PM 01 July 2013
dateTime += " EST"; // append the timezone information to the input string
System.out.println("Input -> " + dateTime);
SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmm z"); // tell the formatter to look for the timezone info
Date date = format.parse(dateTime);
System.out.println("Intermediate -> " + date);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Output -> " + format.format(date));

这也将使用您本地的时区打印 Date 对象,但它展示了一种使用给定时区解析 dateTime 字符串的方法。

关于java - 时区转换期间的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22329798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com