Question

I ve searched many times but I do not find really what I need, I write this to find UTC time zone :

 DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("Europe/Istanbul"));
        String gmtTime = df.format(new Date());
        Date gmtTime_ =null;
        try {
            gmtTime_ = df.parse(gmtTime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  

But I need UTC+2 timezone, How can I get that time zone?

Was it helpful?

Solution

If you are willing to switch to a decent date-time library instead of the notoriously troublesome java.util.Date and java.util.Calendar classes bundled with Java, then read the example code below.

The two decent libraries for Java are Joda-Time and the new java.time package bundled with Java 8 (inspired by Joda-Time, defined by JSR 310).

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