Merve Gül
Merve Gül

Reputation: 1397

Dateformat is not return true time - Java

This code gave me 09:40 (I am in Turkey) but my time is now 12:40 I looked through many pages for this, but I couldnt find any solution. What should I do to fix it?

            String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss"; 
    Calendar cal = Calendar.getInstance(); 
    String timeZone = cal.getTimeZone().getDisplayName(); 
    System.out.println("timeZone is : " + timeZone ); 
        System.out.println("Current Time in MiliSeconds : " + cal.getTimeInMillis() ); 
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); 
    String time=sdf.format(cal.getTime()); 
    System.out.println(time); 

Also why this code gave 08:27 when my time is 12:40

DateFormat formatterHourSecond = new SimpleDateFormat("HH:mm");
String saatStr = formatterHourSecond.format(tarih);     
System.out.println("Saat : " + saatStr);

Upvotes: 1

Views: 344

Answers (2)

Guillaume Polet
Guillaume Polet

Reputation: 47607

The timezone of your machine is somehow incorrect. Usually this is something done by the OS (through regional settings) and the JVM picks it up. So the best solution is actually to set the correct settings in your OS and after restarting your application, you should get the correct time. This is especially better if you plan on having your application running in different countries.

However, if you really need to force the TimeZone, there are two ways to do that:

  1. Do it on the SimpleDateFormat: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setTimeZone(java.util.TimeZone)

  2. Do it globally for your whole application: TimeZone.setDefault(TimeZone.getTimeZone(...))

Upvotes: 1

dogbane
dogbane

Reputation: 274738

It looks like the TimeZone of your JVM is not correct. Try explicitly setting the TimeZone to Turkey in the SimpleDateFormat object, like this:

SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
sdf.setTimeZone(TimeZone.getTimeZone("Turkey"));
String time=sdf.format(cal.getTime()); 

Upvotes: 2

Related Questions