0

In c#:

DateTime dateTime = DateTime.Parse(text, CultureInfo.InvariantCulture);
string s = dateTime.ToLocalTime().ToString("s", CultureInfo.InvariantCulture));

The text is 2011-06-30T05:48:34Z, and the s is 2011-6-30 13:48:34

In java:

DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// explicitly set timezone of input if needed
df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
java.util.Date dateTime ;
dateTime = df.parse(text);
String s= df.format(dateTime));

but the s is 2011-6-30 05:48:34. How to implement ToLocalTime() function in Java?

guhai
  • 187
  • 1
  • 5
  • 15

3 Answers3

1

First set the date as in UTC and get it into a object

java.util.Date dateTime ;
df.setTimeZone(TimeZone.getTimeZone("UTC"));
datetime = df.parse(text);

//Now set this to the required local timezone
df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

String s= df.format(dateTime));

Now the string should have the proper date

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
1

Your code df.parse(text) parses date from the string using the time zone. And then you format the date in the same time zone. Hence you are getting the same result, and obviously it must work so. Unfortunately simpleDateFormat is not compatible with ISO8601. You could use joda time library, which is more powerful and well designed. Or if you always sure that your input string is always in GMT and ends with Z, then you could use explicit code:

DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
java.util.Date dateTime ;
dateTime = dfParse.parse(text);
String s= df.format(dateTime);
Community
  • 1
  • 1
kan
  • 28,279
  • 7
  • 71
  • 101
-1
try{
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

            Date datetime = new Date();

        System.out.println("date "+sdf.format(datetime));

        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        System.out.println("asia/shanghai "+ sdf.format(datetime));

        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        System.out.println("utc "+sdf.format(datetime));
    }catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Pratik
  • 30,639
  • 18
  • 84
  • 159
  • Calendar is only for date manipulation (e.g. add 2 days to a date). Moreover, in your code the calendar is not used for the topic starter's problem. – kan Aug 09 '11 at 10:02
  • Looks better, but I don't like that the parse method implicitly uses a system default timezone, while UTC is required. – kan Aug 09 '11 at 10:07