开发者

How can I print a Date without timezone?

I have a mobile application where I capture a date/time and send it as miliseconds to a servlet. -For example I capture 12:55 AM in my cellphone and send it to my server-

So, I construct the date from the sent miliseconds 开发者_开发百科and print it with SimpleDateFormat but the time is diferent, it prints 8:55 AM. I know that the problem is because I use 2 diferent timezones, my question is: how can I show that time without apply any timezone to show the same time?

Thanks in advance


You need to use Calendar to change the TimeZone but there is no API for that.

// Change a date in another timezone
public static Date changeTimeZone(Date date, TimeZone zone) {
    Calendar first = Calendar.getInstance(zone);
    first.setTimeInMillis(date.getTime());

    Calendar output = Calendar.getInstance();
    output.set(Calendar.YEAR, first.get(Calendar.YEAR));
    output.set(Calendar.MONTH, first.get(Calendar.MONTH));
    output.set(Calendar.DAY_OF_MONTH, first.get(Calendar.DAY_OF_MONTH));
    output.set(Calendar.HOUR_OF_DAY, first.get(Calendar.HOUR_OF_DAY));
    output.set(Calendar.MINUTE, first.get(Calendar.MINUTE));
    output.set(Calendar.SECOND, first.get(Calendar.SECOND));
    output.set(Calendar.MILLISECOND, first.get(Calendar.MILLISECOND));

    return output.getTime();
}

Link: http://blog.vinodsingh.com/2009/03/date-and-timezone-in-java.html

I think this should work. I haven't extensively tested it.


Calendar and Date objects store their date information in milliseconds in relation to UTC.

(the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC)

This means that Calendar/Date Objects do not store different values for different Time Zones. They always use the same value internally... the format is what normally changes.

Maybe you can use a SimpleDateFormat in your local/default timezone:

SimpleDateFormat sdf = new SimpleDateFormat("S")
Date d = sdf.parse(milliseconds);

You can also try to change the DateFormat's timezone until it matches your expected output.

sdf.setTimeZone(TimeZone.getTimeZone("GMT-8"));
System.out.println(sdf.toString());  

sdf.setTimeZone(TimeZone.getTimeZone("GMT-4"));
System.out.println(sdf.toString()); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜