Question

I convert string to date like this:

String date = Date_.get(position).substring(0,19); 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date testDate = null; 
try {   
    testDate = sdf.parse(date);
}catch(Exception ex){
    ex.printStackTrace();
} 

It works fine, But I am worry about should I need to set timezone? I mean there is a string I have like this: '2014-01-01 00:00:00' so why I need to settimezone if it is needed?

Was it helpful?

Solution

yes you should ... even to get rid of warning :D

you can you Locale.getDefault() like

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault());

also TimeZone.getDefault() ...

//EDIT

public static void main(String[] args) {
    String pattern = "yyyy-MM-dd HH:mm:ss";
    Date date = new Date();
    String defaultFmt = new SimpleDateFormat(pattern).format(date);

    for (Locale locale : Locale.getAvailableLocales()) {
        String localeFmt = new SimpleDateFormat(pattern, locale).format(date);
        if (!localeFmt.equals(defaultFmt)) {
            System.out.println(locale + " " + localeFmt);
        }
    }
}

OTHER TIPS

Yes you need to specify the time zone represented by that particular date-time string.

If you were talking to me on the phone, and you asked me what time it is, wouldn't you also ask me where I am? If I'm in Hawaii I'm going to tell you a different time than if I am in Paris.

The bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time, defined by JSR 310).

A Joda-Time DateTime object does indeed know its assigned time zone, whereas a java.util.Date has no time zone though its toString method applies the JVM's default time zone when generating as string.

Joda-Time

Here is some example code using Joda-Time 2.3.

java.util.Date date = new java.util.Date();

// Convert a Date into a Joda-Time DateTime.
// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Istanbul" );
DateTime dateTime = new DateTime( date, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );

Dump to console…

System.out.println( "date: " + date );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );

When run…

date: Mon Mar 31 08:13:37 PDT 2014
dateTime: 2014-03-31T18:13:37.314+03:00
dateTimeUtc: 2014-03-31T15:13:37.314Z
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top