0

I have written a Java Program which takes the current IST timing and generates a report. This report should to be generated at 6pm IST, this check is done in the code itself after fetching IST timezone:

Date dateStr = Calendar.getInstance(TimeZone.getTimeZone("Asia/Kolkata")).getTime();

Problem Area: We are executing that java file in the server in PD timezone and the app is failing and no report is generated because dateStr value is being overwritten by the PD time zone.

Please help me with this as I am not clear like why PD time is shown when I am using IST time in date variable from the code.

Nikhil
  • 65
  • 1
  • 8
  • use **cron scheduler**. refer this answer **https://stackoverflow.com/questions/27221438/cron-every-day-at-6pm** – Night Programmer Mar 16 '18 at 13:25
  • 2
    Your code line could be shortened to the equivalent expression `Date dateStr = new Date();` because you just query the current time which does not depend on any timezone. – Meno Hochschild Mar 16 '18 at 13:26
  • Thanks @MenoHochschild I got the issue now. I've set the timezone for SimpleDateFormat to IST and converted the date object (where Date date = new Date()) – Nikhil Mar 16 '18 at 16:29
  • Exactly, if you want to or must use such an old Time-API then it is best practice not to rely on `java.util.Date.toString()` but to use a properly zoned instance of `SimpleDateFormat`. – Meno Hochschild Mar 16 '18 at 16:39

1 Answers1

1

Your dateStr variable is not being overwritten by any timezone, because a java.util.Date doesn't have any timezone information.

What it does, though, is to use the JVM default timezone when you print it: https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/

Either you System.out.println it, or log it with your favorite logging API (such as log.info(date)), or even check its value in a debugger. All of those implicity calls toString(), and this method just "converts" the date to the JVM default timezone (actually, the Date object doesn't change, just the String).

If you want a timezone-aware object, you could use the Calendar instance. Or even better, if you have Java 8 or higher, just go with the date/time API.

By the way, as said in the comments, Calendar.getInstance(timezone).getTime() will return the same as new Date(), so you must include more code in your question, showing how you're using the date, otherwise we can't know what you're doing and how to fix it.

watssu
  • 57
  • 4