【问题标题】:Convert Local time to UTC and vice versa将本地时间转换为 UTC,反之亦然
【发布时间】:2016-09-20 06:43:36
【问题描述】:

我正在开发 Android 应用程序,我想将本地时间(设备时间)转换为 UTC 并将其保存在数据库中。从数据库中检索它后,我必须再次转换它并显示在设备的时区中。谁能建议如何在 Java 中做到这一点?

【问题讨论】:

    标签: java android time


    【解决方案1】:

    我使用这两种方法将本地时间转换为 GMT/UTC,反之亦然,这对我来说没有任何问题。

    public static Date localToGMT() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date gmt = new Date(sdf.format(date));
        return gmt;
    }
    

    将您要转换为设备本地时间的 GMT/UTC 日期传递给此方法:

    public static Date gmttoLocalDate(Date date) {
    
        String timeZone = Calendar.getInstance().getTimeZone().getID();
        Date local = new Date(date.getTime() + TimeZone.getTimeZone(timeZone).getOffset(date.getTime()));
        return local
    }
    

    【讨论】:

    • 新日期(字符串日期)已弃用。你不应该使用它!
    • 您可以使用 DateFormat.parse(String date) 而不是 new Date(String date),因为它已被弃用。
    【解决方案2】:

    已接受答案的简化和浓缩版本:

    public static Date dateFromUTC(Date date){
        return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(new Date().getTime()));
    }
    
    public static Date dateToUTC(Date date){
        return new Date(date.getTime() - Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
    }
    

    【讨论】:

    • 是的,这是一个简单的正确答案,好朋友。
    • 但 TimeZone#getOffset() 接受 UTC 时间...
    • 我建议编辑,但已被拒绝,第一个函数(即dateFromUTC)有一个错误。如果输入date 参数是UTC,我们必须加上本地时间的时差才能达到本地时间。那么一定是这样的return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(new Date().getTime()));.
    【解决方案3】:

    试试这个:
    //将UTC转换为本地格式

     public Date getUTCToLocalDate(String date) {
                Date inputDate = new Date();
                if (date != null && !date.isEmpty()) {
                    @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                    try {
                        inputDate = simpleDateFormat.parse(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                return inputDate;
            }  
    

    //将本地日期转换为UTC

    public String getLocalToUTCDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date time = calendar.getTime();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        return outputFmt.format(time);
    }
    

    【讨论】:

    • 这是一个可行的解决方案。
    【解决方案4】:

    java.time

    现代方法使用 java.time;类在几年前取代了糟糕的日期时间类,例如 DateCalendar

    以 UTC 格式捕捉当前时刻。

    OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
    

    使用 JDBC 4.2 或更高版本的驱动程序投诉存储在数据库中。

    myPreparedStatement( … , odt ) ;
    

    从数据库中检索。

    OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
    

    调整到时区。

    ZoneId z = ZoneId.systemDefault() ;
    ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
    

    生成文本以呈现给用户。

    DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.getDefault() ) ;
    String output = zdt.format( f ) ;
    

    对于 26 版之前的早期 Android,请使用 ThreeTenABP 库来获取大部分 java.time 功能,这些功能在ThreeTen-Backport 项目。

    【讨论】:

      【解决方案5】:

      你可以尝试这样的东西插入数据库:

          SimpleDateFormat f = new SimpleDateFormat("h:mm a E zz");
          f.setTimeZone(TimeZone.getTimeZone("UTC"));
          System.out.println(f.format(new Date()));
          String dd = f.format(new Date());
      

      这个选项来自你的评论:

      输出:

      世界标准时间周一下午 1:43

      为此,-> 再次转换并显示在设备的时间中

      更新:

      String dd = f.format(new Date());
      
              Date date = null;
              DateFormat sdf = new SimpleDateFormat("h:mm a E zz");
              try {
                  date = sdf.parse(dd);
              }catch (Exception e){
      
              }
              sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
              System.out.println(sdf.format(date));
      

      输出:

      7:30 PM Mon GMT+05:30

      你可能会这样显示。

      【讨论】:

      • 在尝试再次转换时显示空指针异常
      • 不可能,我试过了,效果很好。你能给我你的应用程序的堆栈跟踪吗
      • 我刚刚初始化了 Date date = new Date() 并且工作正常,谢谢
      【解决方案6】:

      Time.getCurrentTimezone()

      将为您提供时区和

      Calendar c = Calendar.getInstance(); int seconds = c.get(Calendar.SECOND)

      将以秒为单位为您提供 UTC 时间。当然,您可以更改该值以获取另一个单位。

      【讨论】:

      • 让我们说如果今天的日期是星期一下午 5:34 (IST) 那么我如何得到它像星期一下午 12:04 (UTC)
      • 您是否真的可以在需要转换的时间访问时间对象,还是只有一个字符串?
      • 我只有一个字符串
      • @Dyo 这应该可以帮助您解决问题。 docs.oracle.com/javase/tutorial/datetime/iso/timezones.html
      【解决方案7】:

      试试这个

      DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
              formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
              Date dateobj = new Date();
              Date date = formatterIST.parse(formatterIST.format(dateobj));
              System.out.println(formatterIST.format(date));
      
              DateFormat formatterUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
              formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
              System.out.println(formatterUTC.format(date));
      

      【讨论】:

        【解决方案8】:

        获取当前 UTC:

        public String getCurrentUTC(){
                Date time = Calendar.getInstance().getTime();
                SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
                return outputFmt.format(time);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-20
          • 2015-04-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多