Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

java - Parsing an ISO 8601 string local date-time as if in UTC

In java I need to make a Calendar object from a String in the format:

yyyy-MM-dd'T'HH:mm:ss

This string will always be set as GMT time. So here's my code:

    public static Calendar dateDecode(String dateString) throws ParseException
{
    TimeZone t = TimeZone.getTimeZone("GMT");
    Calendar cal = Calendar.getInstance(t);
    date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date d = date.parse(dateString);
    cal.setTime(d);
    return cal;
}

And then:

Calendar cal = Calendar.getInstance();
    try
    {
        cal = dateDecode("2002-05-30T09:30:10");
    } catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    int month =  cal.get(Calendar.MONTH)+1;

And I get the following output:

Timezone: GMT+00:00 date: 2002-5-30 time: 7:30:10

Which is as you can see wrong since the time provided is in GMT and not CET. I think what happens is that it think the time provided is in CET (which is my current timezone) and therefore converts the time from CET to GMT and therefore deducts two hours from the final result.

Could anyone help me with this?

Thanks

Btw: I do not wish to use JodaTime for different reasons.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is some code that could help you out with setting the timzones before parsing them:

// sdf contains a Calendar object with the default timezone.
Date date = new Date();
String formatPattern = ....;
SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);

TimeZone T1;
TimeZone T2;
....
....
// set the Calendar of sdf to timezone T1
sdf.setTimeZone(T1);
System.out.println(sdf.format(date));

// set the Calendar of sdf to timezone T2
sdf.setTimeZone(T2);
System.out.println(sdf.format(date));

// Use the 'calOfT2' instance-methods to get specific info
// about the time-of-day for date 'date' in timezone T2.
Calendar calOfT2 = sdf.getCalendar();

another similar question I found might help too: How to set default time zone in Java and control the way date are stored on DB?

EDIT:

Here is a great tutorial on Java & Dates too: http://www.tutorialspoint.com/java/java_date_time.htm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...