【问题标题】:How can I get time from specific timezone?如何从特定时区获取时间?
【发布时间】:2016-03-01 16:13:46
【问题描述】:

我有一个时区,我有:

TimeZone tz = TimeZone.getTimeZone("GMT-05:00"); 日历 c = Calendar.getInstance(tz);

如何从该时区获取具有正确时间的DateTime 对象?
如果我这样做c.getTime(),我会得到当前时间,而不是那个时区的时间。
在做

String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
            String.format("%02d" , c.get(Calendar.MINUTE))+":"+
.                   String.format("%02d" , c.get(Calendar.SECOND))+":"+
    .           String.format("%03d" , c.get(Calendar.MILLISECOND));

我得到了预期的时间,但我无法从此字符串创建有效的DateTime 对象。
我该如何解决这个问题?

【问题讨论】:

  • 您使用哪个版本的 Java? 8个或更少?
  • 你提到了jodatime作为标签;你真的使用它吗?您的代码仅依赖于旧 API
  • 如果您希望DateTime 有一个时区,您需要使用DateTimeZone 将该时区设置为DateTime。你为什么要把 java.util.Calendar 和 Joda-Time 混在一起?
  • @fge:是的,如果 JodaTime 有解决方案,我可以使用它。
  • @RealSkeptic:我正在使用通过搜索找到的代码。有没有更好/另一种方法?

标签: java datetime jodatime


【解决方案1】:
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// GMT-5
df.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
String strDate = df.format(date);
System.out.println("Date and time in GMT-5: " + strDate);

【讨论】:

    【解决方案2】:

    其他获取和打印时区时间的可能性包括:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    
    public class TestDate {
    
        public static void main(String[] args){
            Date date = new Date();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            String dateString = df.format(date);
    
            System.out.println(dateString);
        }
    }
    

    【讨论】:

      【解决方案3】:

      你需要使用DateTime.WithZone方法

      TimeZone timeZone = TimeZone.getTimeZone("GMT-05:00");
          DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(timeZone);
          System.out.println(timeZone);
          System.out.println(dateTimeZone);
          DateTime dt = new DateTime();
          DateTime dtLondon = dt.withZone(dateTimeZone);
          System.out.println(dtLondon);
      

      【讨论】:

      • 我没有forId 部分的信息
      • 好的,我明白了,请查看更新后的答案...@Jim
      【解决方案4】:

      查看此链接可能会有所帮助

      TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
      Calendar c = Calendar.getInstance(tz);
      String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
                  String.format("%02d" , c.get(Calendar.MINUTE))+":"+
      .                   String.format("%02d" , c.get(Calendar.SECOND))+":"+
          .           String.format("%03d" , c.get(Calendar.MILLISECOND));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-23
        • 1970-01-01
        • 2021-09-22
        • 2015-03-25
        • 2021-03-13
        • 2012-01-02
        • 2016-08-23
        • 1970-01-01
        相关资源
        最近更新 更多