-3

My server is using GMT time zone but my application is working on IST, so I am converting GMT to IST while saving to database.But when I am converting this saved IST into epoch time then it's adding 5 hours 30 minutes into the saved IST time.

Is there any idea why? Am I doing anything wrong?

The code for converting GMT to IST:

 public static Date convertGmtToIst(Date date) throws ParseException {
        DateFormat converter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss");
        converter.setTimeZone(TimeZone.getTimeZone("IST"));
        String dateReturns = converter.format(date);
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss");
        Date alteredDate = formatter.parse(dateReturns);
        return alteredDate;
    }

This is the code i am using to convert IST(2018-01-24 15:51:01) to epoch time.the date i am passing in this method is 2018-01-24 15:51:01 so this method should returns the epoch time of this date but it's adding 5 hours 30 minutes into this time.

public static long getEpochDateTime(Date date) {
        long epochDateTime = date.getTime();
        return epochDateTime;
    }
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Can you please provide the code that you are using for conversions from GMT to IST and vice-versa? – Prashant Jan 24 '18 at 06:36
  • @Prashant public static Date convertGmtToIst(Date date) throws ParseException { DateFormat converter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss"); converter.setTimeZone(TimeZone.getTimeZone("IST")); String dateReturns = converter.format(date); SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss"); Date alteredDate = formatter.parse(dateReturns); return alteredDate; } –  Jan 24 '18 at 07:02
  • 1
    Search Stack Overflow before posting. This has been covered many many times already. Hint: `java.time.Instant`. – Basil Bourque Jan 24 '18 at 07:45
  • Better to save UTC time to the database. See [Best practices with saving datetime & timezone info in database when data is dependant on datetime](https://stackoverflow.com/questions/44965545/best-practices-with-saving-datetime-timezone-info-in-database-when-data-is-dep). – Ole V.V. Jan 24 '18 at 10:27
  • 1
    I don’t understand why in 2018 you are still trying to use the long outdated `SimpleDateFormat` class and it equally outdated friend `Date`. [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) is so much nicer to work with. – Ole V.V. Jan 24 '18 at 10:30
  • Possible duplicate of [Convert a date format in epoch](https://stackoverflow.com/questions/6687433/convert-a-date-format-in-epoch) – Ole V.V. Jan 24 '18 at 11:17
  • This question has been asked and answered with minor variations over and over. Please use your search engine to get a good answer faster than anyone can type one here. – Ole V.V. Jan 24 '18 at 11:18
  • Hi @OleV.V. i tried to search my issue on stack-overflow but i didn't get any conversation to solve out my issue. i am saving date in database like 2018-01-24 16:03:03 (IST) but when i convert this IST to epoch time then it's adding 5 hours and 30 minutes in the saved date. here it's my code to convert IST to epoch time public static long getEpochDateTime(Date date) { long epochDateTime = date.getTime(); return epochDateTime; } –  Jan 24 '18 at 11:46
  • 1
    If we’re to stand any chance of helping you in that situation, you must include which answers you’ve looked at (at least a couple of examples) and explain precisely how they were insufficient or failed to solve your problem. Otherwise we can only use our energy repeating what it says in those useless answers, for the benefit of no one. – Ole V.V. Jan 24 '18 at 12:05
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) And this one: [Stack Overflow question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Please. – Ole V.V. Jan 24 '18 at 12:07
  • @OleV.V. I have tried this answer https://stackoverflow.com/questions/6687433/convert-a-date-format-in-epoch but still not able to solve the issue –  Jan 24 '18 at 12:08
  • There’s no way in the world I (or anyone else here) can help you with that as long as you don’t explain in detail what went wrong when you tried. And please add that information in the question itself, not in comments. – Ole V.V. Jan 24 '18 at 12:09
  • @OleV.V. i have updated a function getEpochDateTime by which i am converting the saved IST to epoch time –  Jan 24 '18 at 12:10
  • The code you have added is correct. Your problem must be somewhere else. – Ole V.V. Jan 24 '18 at 12:11
  • Both the functions are correct . getEpochDateTime() convertGmtToIst() ?? –  Jan 24 '18 at 12:13

2 Answers2

1

tl;dr

Use smart objects, not dumb strings.

Instant.now().toEpochMilli()

Or:

myDate.toInstant().toEpochMilli()

Details

As discussed many times already on Stack Overflow…

My server is using GMT time zone

Never depend on the server OS settings for time zone. Always specify the optional time zone argument passed to the java.time classes’ methods.

converting GMT to IST while saving to database

Do most of your work in UTC. Adjust into another time zone only when business logic so dictates, or for presentation to user.

DateFormat converter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss");

Work with date-time objects rather than mere strings.

Never use the troublesome Date and Calendar classes. Now supplanted by the java.time classes.

Never use 3-4 character pseudo-time zone codes such as IST. They are not true time zones, not standardized, and not even unique(!). Use true time zones in continent/region format.

ZoneId z = ZoneId.of( “Asia/Kolkata” ) ;

Get current moment in UTC.

Instant instant = Instant.now() ; 

If your code must interoperate with Date, use new methods on old classes to convert to-and-fro.

Instant instant = myJavaUtilDate.toInstant() ;

Generate a string to represent this moment in standard ISO 8601 format by calling toString.

String output = instant.toString() ;

Adjust into another time zone. Same moment, same point on the timeline, different wall-clock time.

ZonedDateTime zdt = Instant.atZone( z ) ;  // Same moment, different wall-clock time.

Call toString to generate a string with a format that wisely extends the ISO 8601 format by appending the name of the time zone in square brackets.

String output = zdt.toString() ;

To generate a string in other formats, see the DateTimeFormatter class.

You can move from a zoned moment to UTC by extracting an Instant.

Instant instant = zdt.toInstant() ;

returns the epoch time

Tracking time as a count-from-epoch is bad practice. But if you insist, you can extract a count of milliseconds from first moment of 1970 in UTC. Beware of data loss as Instant has a resolution of nanoseconds.

long millis = instant.toEpochMilli() ;

Get an Instant again. Again, I recommend against using a count-from-epoch, but if you insist.

Instant instant = Instant.ofEpochMilli( millis ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You should probably include timezone when serializing the date. new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

Ankit Gupta
  • 275
  • 3
  • 12