10

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i execute my program at a particular time.. My output is ::

The current time in India is :: Fri Feb 24 16:09:23 IST 2012

The date and time in :: Central Standard Time is :: Sat Feb 25 03:39:23 IST 2012

And the actual Time according to CST time zone is ::

Friday, 24 February 4:39:16 a.m(GMT - 6:00)

So there's some time gap. and i don't know why this is happening. Any help will be appreciated.. The code is ::

package MyPackage;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Temp2 {


    public static void main(String[] args) {

        try {
            Calendar currentdate = Calendar.getInstance();
            String strdate = null;
            DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            strdate = formatter.format(currentdate.getTime());
            TimeZone obj = TimeZone.getTimeZone("CST");

            formatter.setTimeZone(obj);
            //System.out.println(strdate);
            //System.out.println(formatter.parse(strdate));
            Date theResult = formatter.parse(strdate);

            System.out.println("The current time in India is  :: " +currentdate.getTime());

            System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
        } catch (ParseException e) {
           e.printStackTrace();
        }
    }
}
4

11 回答 11

21

它在网络上。本来可以用谷歌搜索的。无论如何,这是给你的版本(无耻地从这里挑选和修改):

Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone("CST");

calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
    calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}

calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
    calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}

System.out.println(calendar.getTime());
于 2012-02-24T11:04:07.453 回答
8

您的错误是调用parse而不是format.

您调用parse从字符串解析日期,但在您的情况下,您有一个日期,需要使用正确的时区对其进行格式化。

将您的代码替换为

Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
System.out.println("Local:: " +currentdate.getTime());
System.out.println("CST:: "+ formatter.format(currentdate.getTime()));

我希望你能得到你期望的输出。

于 2012-02-24T11:00:10.627 回答
6

SimpleDateFormat#setTimezone()是答案。一个带有时区的格式化程序ETC用于解析,另一个UTC用于生成输出字符串:

DateFormat dfNy = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfNy.setTimeZone(TimeZone.getTimeZone("EST"));
DateFormat dfUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
dfUtc.setTimeZone(TimeZone.getTimeZone("UTC"));

try {
    return dfUtc.format(dfNy.parse(input));
} catch (ParseException e) {
    return null;              // invalid input
}
于 2015-10-21T14:28:39.143 回答
4

在我的日常工作中用 Java 处理日期是一项非常重要的任务。我建议您使用Joda-Time来简化我们的编码时间,并且您不必“重新发明轮子”。

于 2012-02-24T11:08:03.353 回答
3

您可以使用两种 SimpleDateFormat,一种用于解析带有 EST 时区的日期字符串,一种用于打印带有 UTC 时区的日期

String format = "yyyy-MM-dd HH:mm:ss";
    SimpleDateFormat estFormatter = new SimpleDateFormat(format);
    estFormatter.setTimeZone(TimeZone.getTimeZone("EST"));
    Date date = estFormatter.parse("2015-11-01 01:00:00");

    SimpleDateFormat utcFormatter = new SimpleDateFormat(format);
    utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));

    System.out.println(utcFormatter.format(date));
于 2015-10-21T14:26:28.347 回答
2

问题是当您打印日期 obj 它调用toString方法时,它将在您的机器默认时区打印。试试这个代码,看看有什么不同。

Calendar currentdate = Calendar.getInstance();
String strdate = null;
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ssz");
strdate = formatter.format(currentdate.getTime());
System.out.println("strdate=>" + strdate);
TimeZone obj = TimeZone.getTimeZone("CST");

formatter.setTimeZone(obj);
strdate = formatter.format(currentdate.getTime());
Date theResult = formatter.parse(strdate);

System.out.println("The current time in India is  :: " +currentdate.getTime());

System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + theResult);
System.out.println("The date and time in :: " + obj.getDisplayName() + "is ::" + strdate);
于 2012-02-24T11:28:30.883 回答
2

您可以只使用“CST6CDT” ,因为在某些国家/地区,他们在夏季使用 CDT,而在冬季使用 CST

 public static String getDateInCST() {
             Calendar calendar = Calendar.getInstance();
             DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
             formatter.setTimeZone(TimeZone.getTimeZone( "CST6CDT"));
             String strdate = formatter.format(calendar.getTime());
             TimeZone.getAvailableIDs();
             return strdate;
     }
于 2017-03-31T07:03:57.307 回答
1

第一条消息,不要将您的日期和时间作为代码中的字符串处理。就像您不将数字和布尔值作为字符串处理一样(我希望如此)。使用适当的日期时间对象。

java.time

有时我们将日期和时间作为字符串输入。例如,它可能来自文本文件、来自用户或来自与另一个系统的数据交换。在这些情况下,首先要解析为适当的日期时间对象。第二条消息,使用现代 Java 日期和时间 API java.time 进行日期和时间工作。

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

    String input = "2015-11-01 01:00:00";

    ZonedDateTime nyTime = LocalDateTime.parse(input, formatter)
            .atZone(ZoneId.of("America/New_York"));
    System.out.println("Time in New York: " + nyTime);

此片段的输出是:

Time in New York: 2015-11-01T01:00-04:00[America/New_York]

要转换为 GMT:

    OffsetDateTime gmtTime = nyTime.toOffsetDateTime()
            .withOffsetSameInstant(ZoneOffset.UTC);
    System.out.println("GMT Time: " + gmtTime);
GMT Time: 2015-11-01T05:00Z

如果您需要提供字符串输出,请使用日期时间格式化程序进行格式化。以下是针对美国观众的格式化示例:

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
                    .withLocale(Locale.US);
    String formattedDateTime = gmtTime.format(userFormatter);
    System.out.println("GMT Time formatted for user: " + formattedDateTime);
GMT Time formatted for user: Nov 1, 2015, 5:00:00 AM

您还问:

在以下两个结果之间,您应该选择哪一个?

我理解你问,因为两者都是有效的答案。2015 年 11 月 1 日夏令时 (DST) 于凌晨 2 点结束。也就是说,在 01:59:59 之后第二次是 01:00:00。所以当我们有2015-11-01 01:00:00输入时,它是模棱两可的。它可能是东部夏令时间,等于格林威治标准时间 05:00,也可能是东部标准时间,一小时后,因此等于格林威治标准时间 06:00。我无法告诉你哪一个在你的情况下是正确的。您可以控制使用withEarlierOffsetAtOverlap()或获得的结果withLaterOffsetAtOverlap()。上面我们得到了夏令时的解释。所以要获得标准时间解释:

    nyTime = nyTime.withLaterOffsetAtOverlap();
    System.out.println("Alternate time in New York: " + nyTime);

纽约候补时间:2015-11-01T01:00-05:00[America/New_York]

我们注意到一天中的小时仍然是 01:00,但偏移量现在是-05:00而不是-04:00. 这也给了我们不同的 GMT 时间:

GMT Time: 2015-11-01T06:00Z
GMT Time formatted for user: Nov 1, 2015, 6:00:00 AM

避免 SimpleDateFormat 和朋友

虽然其他答案通常是正确的,但那里的 classes 、DateFormat和used设计不佳且早已过时。前两个特别麻烦。我建议你避免所有这些。坦率地说,我发现现代 API 更易于使用。SimpleDateFormatDateCalendar

关联

Oracle 教程:日期时间解释如何使用 java.time。

于 2020-04-05T12:25:45.317 回答
0

2020在这里回答

如果您想要新java.time.*功能但仍想弄乱java.util.Date

 public static Date convertBetweenTwoTimeZone(Date date, String fromTimeZone, String toTimeZone) {
        ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
        ZoneId toTimeZoneId = ZoneId.of(toTimeZone);

        ZonedDateTime fromZonedDateTime =
                ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).withZoneSameLocal(fromTimeZoneId);

        ZonedDateTime toZonedDateTime = fromZonedDateTime
                .withZoneSameInstant(toTimeZoneId)
                .withZoneSameLocal(ZoneId.systemDefault())
                ;

        return Date.from(toZonedDateTime.toInstant());
    }

为了java.sql.Timestamp

    public static Timestamp convertBetweenTwoTimeZone(Timestamp timestamp, String fromTimeZone, String toTimeZone) {

        ZoneId fromTimeZoneId = ZoneId.of(fromTimeZone);
        ZoneId toTimeZoneId = ZoneId.of(toTimeZone);

        LocalDateTime localDateTimeBeforeDST = timestamp.toLocalDateTime();

        ZonedDateTime fromZonedDateTime = ZonedDateTime.of(localDateTimeBeforeDST, fromTimeZoneId);

        ZonedDateTime toZonedDateTime = fromZonedDateTime.withZoneSameInstant(toTimeZoneId);

        return Timestamp.valueOf(toZonedDateTime.toLocalDateTime());
    }
于 2020-07-07T19:10:36.113 回答
0

对于谷歌日历 API

private String getFormatedDate(Date date)
    {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+05:30");
        df.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
        return df.format(date);
    }
于 2021-07-23T16:32:50.253 回答
0

请参考下面提到的代码。

     DateFormat utcConverter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     utcConverter.setTimeZone(TimeZone.getTimeZone("GMT"));
     String sampleDateTime = "2015-11-01 01:00:00";
     DateFormat nyConverter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     nyConverter.setTimeZone(TimeZone.getTimeZone("EST"));
     Calendar nyCal = Calendar.getInstance();

     nyCal.setTime(nyConverter.parse(sampleDateTime));

     System.out.println("NY TIME :" +nyConverter.format(nyCal.getTime()));

    System.out.println("GMT TIME  :" +utcConverter.format(nyCal.getTime()));
于 2015-10-21T14:50:47.990 回答