Convert Date to Milliseconds in Java

I need to convert a Date to its corresponding Milliseconds format.I am using getTime() method of Date class in Java for this. But the milliseond generated is not of my actual date. It is one day less than my date. For eg,

I have 22-Nov-2014. If I convert this date to milliseconds format then 1,416,594,600,000 is generated. Actually this value corresponds to 21-Nov-2014.

Please help me to get an exact milliseconds value corresponds to a Date in java.

Jon Skeet
people
quotationmark

1416594600000 corresponds to 2014-11-21T18:30:00Z. In other words, 6.30pm on November 21st 2014 in UTC. Epoch Converter is a great resource for checking things like that.

Now, a Date object doesn't have any time zone information itself. It just represents a point in time. It sounds like your "22-Nov-2014" value was probably midnight in the local time zone (India?). If you are generating values from lots of different time zones and you don't store which time zone goes with which value, you've essentially lost some information here.

If you're trying to just represent a date (rather than a point in time) but you have to store it as a milliseconds-since-the-unix-epoch value, it probably makes sense to store midnight of that date in UTC, although you should also make it very clear that that's what you're doing. If you can, you should store the value in some way that makes it more obvious it's a date - such as using a DATE field in a database. Date and time work is often really not as hard as we fear it to be if you know exactly what data you're modelling, and make that very clear everywhere in your code.

One way to make things clearer is to use a good date/time API which allows you to represent more kinds of data than java.util.Date and java.util.Calendar do. Joda Time is good for this, and Java 8 has the new java.time.* API. I'd strongly advise you to move to one of those as soon as possible.

people

See more on this question at Stackoverflow