【问题标题】:Local time to EST time Conversion当地时间与美国东部时间时间换算
【发布时间】:2015-09-24 22:29:18
【问题描述】:

Android 本地时间到美国东部时间的转换

代码:

SimpleDateFormat serverDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
serverDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Calendar calender= Calendar.getInstance(Locale.getDefault());
String  time=serverDateFormat.format(calender.getTime());

但我得到了错误的时间。 与正确时间相差一小时。 例如: 当地时间:2015 年 7 月 7 日星期二 17:30:00 GMT+05:30 形成时间:2015/07/07 07:00:00 正确时间:2015/07/07 08:00:00

【问题讨论】:

    标签: android date timezone simpledateformat


    【解决方案1】:

    您的问题是使用代表“东部标准时间”的标识符“EST”。顾名思义,它不使用夏令时规则。证明:

    TimeZone tz = TimeZone.getTimeZone("EST");
    long offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
    System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
    // output: EST:false/-5
    

    改用时区 ID“America/New_York”:

    tz = TimeZone.getTimeZone("America/New_York");
    offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
    System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
    // output: America/New_York:true/-4
    

    然后您将观察到 7 月的夏令时,产生 (+05:30) - (-04:00) = +09:30 的偏移差,从而导致预计当地时间上午 8 点。

    【讨论】:

    • 如何使用这个偏移量来获得准确的 UTC -0 日期时间??
    • 你能用适当的例子解释一下吗?
    • @VishalHalani 通常您不需要进行偏移计算。如果你有 java.util.Date 或自 unix 纪元以来的毫秒数,那么它已经是 UTC。但是偏移量在SimpleDateFormat 中间接用于本地日期显示和java.util.Date 类型的对象之间的转换。如果您想将本地时间戳解释为 UTC,则只需在 SimpleDateFormat 上将区域设置为“GMT”或“UTC”。
    • 我将日期时间转换为 UTC-0 伦敦时区,因此当我将它插入到共享点时,它从现在开始为 -5:30,它在 UTC-0 时间显示 +1 小时。意思是如果我添加 7.30 UTC 时间,那么我可以看到 8.30 条目
    • @VishalHalani 你的评论对我来说不是很清楚。我建议您使用简短、完整和可编译的示例打开一个关于 SO 的新问题,并显示您的输入和输出以及您的期望。您的问题似乎甚至可能涉及 Microsoft Sharepoint,这是完全不同的(甚至在 Java 之外)。
    【解决方案2】:

    嘿,请试试这个function 时间conversion -

        public static String getTime(String time, SimpleDateFormat sdf) {
        String convertedTime = "";
    
        try {
            TimeZone timeZone = TimeZone.getDefault();
            Date postdate = sdf.parse(time);
            long postTimeStamp = postdate.getTime() + timeZone.getRawOffset();
    
            String dateString = sdf.format(new Date(postTimeStamp));
    
            convertedTime = dateString;
    
    
            // convertedTime = getLastTime(context, time);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return convertedTime;
    }
    

    【讨论】:

    • 你能解释一下为什么 OP 应该这样做而不是他目前在做什么?
    • @Prera​​k - 他可以修改我的功能,但根据我的要求,日期格式太多了,为什么我们会依赖服务器时区。
    猜你喜欢
    • 2022-06-29
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多