Date.getTime() not including time?
Asked Answered
U

9

7

Can't understand why the following takes place:

String date = "06-04-2007 07:05";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date myDate = fmt.parse(date); 

System.out.println(myDate);  //Mon Jun 04 07:05:00 EDT 2007
long timestamp = myDate.getTime();
System.out.println(timestamp); //1180955100000 -- where are the milliseconds?

// on the other hand...

myDate = new Date();
System.out.println(myDate);  //Tue Sep 16 13:02:44 EDT 2008
timestamp = myDate.getTime();
System.out.println(timestamp); //1221584564703 -- why, oh, why?
Upstretched answered 16/9, 2008 at 17:8 Comment(2)
There is no seconds either, because you haven't given any in the date!Naumachia
Uhm, I see them there, the last three 0's. You've set them to 0 implicitly.Heliometer
F
21

What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?

String date = "06-04-2007 07:05:00.999";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S");
Date myDate = fmt.parse(date);

System.out.println(myDate); 
long timestamp = myDate.getTime();
System.out.println(timestamp);
Fairhaired answered 16/9, 2008 at 17:11 Comment(4)
There are no seconds or minutes or hours either! getTime() returns only the long integer representing the date from time 00:00:00. There is no possibility of parsing seconds: they are simply not present in my data. =)Upstretched
Why don't you open a new question with your actual code and a bit of sample data if this hasn't solved your doubt? I guess your problem might be somewhere else.Fairhaired
1180955100000 does contain an hour and a minute component as would be expected. You should accept Vinko's answer.Humpback
Yeah, I realized I was just being stupid. I was printing the object and it was displaying only the date, despite the time data being present. Thanks for the help!Upstretched
N
2

Because simple date format you specified discards the milliseconds. So the resulting Date object does not have that info. So when you print it out, its all 0s.

On the other hand, the Date object does retain the milliseconds when you assign it a value with milliseconds (in this case, using new Date()). So when you print them out, it contains the millisecs too.

Not answered 16/9, 2008 at 17:14 Comment(0)
E
2

Instead of using the Sun JDK Time/Date libraries (which leave much to be desired) I recommend taking a look at http://joda-time.sourceforge.net.

This is a very mature and active sourceforge project and has a very elegant API.

Eveland answered 17/9, 2008 at 1:34 Comment(0)
F
1

tl;dr

The accepted Answer by Vinko Vrsalovic is correct. Your input is whole minutes, so the milliseconds for fractional second should indeed be zero.

Use java.time.

LocalDateTime.parse
( 
    "06-04-2007 07:05" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm" ) 
)
.atZone
(
    ZoneId.of( "Africa/Casablanca" ) 
)
.toInstant()
.getEpochMilli()

java.time

The modern approach uses the java.time classes defined in JSR 310 that years ago supplanted the terrible classes you are using.

Define a formatting pattern to match your input. FYI: Learn to use standard ISO 8601 formats for exchanging date-time values as text.

String input = "06-04-2007 07:05" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm" ) ;

Parse your input as a LocalDateTime, as it lacks an indicator of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

This represents a date and a time-of-day, but lacks the context of a time zone or offset. So we do not know if you meant 7 AM in Tokyo Japan, 7 AM in Toulouse France, or 7 AM in Toledo Ohio US. This issue of time zone is crucial, because your desired count of milliseconds is a count since the first moment of 1970 as seen in UTC (an offset of zero hours-minutes-seconds), 1970-01-01T00:00Z.

So we must place your input value, the LocalDateTime object, in the context of a time zone or offset.

If your input was intended to represent a date and time in UTC, use OffsetDateTime with ZoneOffset.UTC.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;  // Do this if your date and time represent a moment as seen in UTC. 

If your input was intended to represent a date and time as seen through the wall-clock time used by the people of a particular region, use ZonedDateTime.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

Next we want to interrogate for the count of milliseconds since the epoch of first moment of 1970 in UTC. With either a OffsetDateTime or ZonedDateTime object in hand, extract a Instant by calling toInstant.

Instant instant = odt.toInstant() ;

…or…

Instant instant = zdt.toInstant() ;

Now get count of milliseconds.

long millisecondsSinceEpoch = instant.toEpochMilli() ;

By the way, I suggest you not track time by a count of milliseconds. Use ISO 8601 formatted text instead: easy to parse by machine, easy to read by humans across cultures. A count of milliseconds is neither.


Table of date-time types in Java, both modern and legacy


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.

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Ferroelectric answered 2/5, 2020 at 22:37 Comment(0)
H
0

When you parse a date it only uses the information you provide. In this case it only knows MM-dd-yyyy HH:mm.

Creating a new date object returns the current system date/time (number of milliseconds since the epoch).

Humpback answered 16/9, 2008 at 17:14 Comment(0)
P
0

toString() of a Date object does not show you the milliseconds... But they are there

So new Date() is an object with milisecond resolution, as can be seen by:

  System.out.printf( "ms = %d\n", myDate.getTime() % 1000 ) ;

However, when you construct your date with SimpleDateFormat, no milliseconds are passed to it

Am I missing the question here?

[edit] Hahaha...way too slow ;)

Pinfeather answered 16/9, 2008 at 17:15 Comment(0)
A
0

Date.getTime returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by the Date object. So "06-04-2007 07:05" - "01-01-1970 00:00" is equal to 1180955340000 milliseconds. Since the only concern of your question is about the time portion of the date, a rough way of thinking of this calculation is the number of milliseconds between 07:05 and 00:00 which is 25500000. This is evenly divisible by 1000 since neither time has any milliseconds.

In the second date it uses the current time when that line of code is executed. That will use whatever the current milliseconds past the current second are in the calculation. Therefore, Date.getTime will more than likely return a number that is not evenly divisible by 1000.

Assumed answered 16/9, 2008 at 18:1 Comment(0)
A
0

The getTime() method of Date returns the number of milliseconds since January 1, 1970 (this date is called the "epoch" because all computer dates are based off of this date). It should not be used to display a human-readable version of your Date.

Use the SimpleDateFormat.format() method instead. Here is a revised version of part of your code that I think may solve your problem:

String date = "06-04-2007 07:05:23:123";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss:S");
Date myDate = fmt.parse(date); 

System.out.println(myDate);  //Mon Jun 04 07:05:23 EDT 2007
String formattedDate = fmt.format(myDate);
System.out.println(formattedDate); //06-04-2007 07:05:23:123
Approximate answered 16/9, 2008 at 19:27 Comment(0)
C
0
import java.util.*;

public class Time {
    public static void main(String[] args) {
        Long l = 0L;
        Calendar c = Calendar.getInstance();
        //milli sec part of current time
        l = c.getTimeInMillis() % 1000;  
        //current time without millisec
        StringBuffer sb = new StringBuffer(c.getTime().toString());
        //millisec in string
        String s = ":" + l.toString();
        //insert at right place
        sb.insert(19, s);
        //ENJOY
        System.out.println(sb);
    }
}
Centuple answered 15/3, 2009 at 3:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.