按时区转换日期

Convert Date by TimeZone(按时区转换日期)
本文介绍了按时区转换日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在上面的代码中,我想将服务器的时区 (GMT-02:00) 的日期转换为我的设备 (GMT-03:00) 的时区.但我总是有相同的服务器日期.我做错了什么?

In that code above I want to transform a Date by the TimeZone of Server (GMT-02:00) to TimeZone from my Device (GMT-03:00). But I Always have the same Date of the server. What I doing wrong?

时区 timeZoneServer = TimeZone.getTimeZone(timeZoneServerString);长时间 = new Long(Long.valueOf(timeInMilis));

TimeZone timeZoneServer = TimeZone.getTimeZone(timeZoneServerString); Long time = new Long(Long.valueOf(timeInMilis));

        Calendar calendarDateServer =   Calendar.getInstance(timeZoneServer);
        calendarDateServer.setTimeInMillis(time);
        long miliServer = calendarDateServer.getTimeInMillis();

        TimeZone timeZoneMeu = TimeZone.getDefault();
        Calendar meuCalendario =  new GregorianCalendar();
        meuCalendario.setTimeZone(timeZoneMeu);

        meuCalendario.setTimeInMillis(miliServer);  
        Date transformedDate = meuCalendario.getTime();


        return transformedDate; 

推荐答案

我做错了什么?

您假设 Date 有一个时区作为开始.它没有.Calendar 可以,但 Date 自 Unix 纪元以来只有 毫秒.它不知道日历系统或时区.这只是一个时间点.

You're assuming that a Date has a time zone to start with. It doesn't. A Calendar does, but a Date is just milliseconds since the Unix epoch. It doesn't know about calendar systems or time zones. It's just a point in time.

不清楚你想对结果做什么 - 但如果它是格式化显示的问题,只需使用 SimpleDateFormat 并在 that 上设置时区而是.

It's not clear what you want to do with the result - but if it's a matter of formatting it for display, just use SimpleDateFormat and set the time zone on that instead.

我还强烈建议您使用 Joda Time 而不是内置类型...这是一个更明智的 API.

I would also strongly recommend that you use Joda Time instead of the built-in types... it's a much more sensible API.

这篇关于按时区转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to implement RecyclerView with section header depending on category?(如何根据类别实现带有节标题的 RecyclerView?)
How to generate JNI header file in Eclipse(如何在 Eclipse 中生成 JNI 头文件)
Setting a custom HTTP header dynamically with Spring-WS client(使用 Spring-WS 客户端动态设置自定义 HTTP 标头)
Could you technically call the string[] anything in the main method?(从技术上讲,您可以在 main 方法中调用 string[] 吗?)
What is the proper way of setting headers in a URLConnection?(在 URLConnection 中设置标头的正确方法是什么?)
How to overwrite http-header quot;Hostquot; in a HttpURLConnection?(如何覆盖 http-header “主机在 HttpURLConnection 中?)