views:

105

answers:

3

Hi, I have problem with getting server date (linux server). When I use linux 'date' command I get properly date value (real date). If I modify some file on server, modify date is also properly (real date). But if i use java code System.out.println(new Date()) on server I get date with 1 hour difference i.e. linux 'date' command result = Wed Sep 16 08:48:25 CEST, System.out.println(new Date()) result = Wed Sep 16 07:48:25 GMT+1 Is this linux configuration problem or wrong getting date using java. Thanks

date --rfc-2822; date +%s

Wed, 16 Sep 2009 09:59:36 +0200 1253087976

System.out.println(new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").format(new Date()));
System.out.println(new Date().getTime() / 1000);

16 wrz 2009 09:00:33 +0100 1253088033

A: 

This is probably a timezone/daylight savings issue. Use:

java.util.Timezone.getDefault()

to see which timezone is Java configured to use and whether daylight savings apply or not.

kgiannakakis
A: 

I suggest you upgrade your Java installation. Your JRE likely doesn't have the latest daylight savings rules in place. Java gets the time since the epoch, and uses your current TZ setting to compute what the local time is. DST rules change from time to time, and both the operating system and the JDK need to be updated when this occurs.

Can you add the output of the following to your question:

# unix
date --rfc-2822; date +%s

# Java
System.out.println(new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").format(new Date()));
System.out.println(new Date().getTime() / 1000);

The should both output something like:

Wed, 16 Sep 2009 17:26:08 +1000
1253085968
brianegge
A: 

You must make sure you use the correct time zone before using Date (or Calendar, for that matter - wasn't Date deprecated?).

For instance:

/* Skipping the boring class def part. */
public static void main(String[] args) {
    Date date = new Date();
    DateFormat myDateFormat = new SimpleDateFormat();
    TimeZone firstTime = TimeZone.getTimeZone(args[0]);
    myDateFormat.setTimeZone(firstTime);
    System.out.println("-->"+args[0]+": " + myDateFormat.format(date));
}

the argument then can be your desired time zone, for example "IST", "GMT", or whatever.

Michael Foukarakis
Thanks for the answer. It works fine.Date date = new Date();DateFormat myDateFormat = new SimpleDateFormat();firstTime = TimeZone.getTimeZone("Europe/Warsaw");myDateFormat.setTimeZone(firstTime);System.out.println(myDateFormat.format(date));produces output like:16.09.09 10:25
arek