問題描述
在上面的代碼中,我想將服務器的時區 (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.
這篇關于按時區轉換日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!