-1

I have the following function that should return a timestamp. This code works when the date is entered in a string format using slashes like the following: "2019/3/4" but does not work right when using new Date(year, month, day).

import java.util.Date;

public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
}
dateToTimestamp(new Date(2019, 3, 4) ---> 61512498000000 or, when converted, Friday, April 4, 3919 5:00:00 AM

What is going on?

Jason p
  • 103
  • 1
  • 10
  • 1
    ```@Deprecated public Date(int year, int month, int date) { this(year, month, date, 0, 0, 0); }``` It's a deprecated method. Also add the error you're getting. – Shahal Dec 28 '19 at 16:42
  • try `2019-1990` instead of `2019` – oybek Dec 28 '19 at 16:44
  • @Shahal I am not getting an error logged anywhere as the value is just wrong after converted. – Jason p Dec 28 '19 at 16:47
  • Does this answer your question? [Creating java date object from year,month,day](https://stackoverflow.com/questions/16499228/creating-java-date-object-from-year-month-day) I recommend [the answer by przemek](https://stackoverflow.com/a/33892250/5772882). – Ole V.V. Dec 28 '19 at 21:49
  • 1
    I recommend you consider throwing away the long outmoded and poorly designed `Date` class and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. And I certainly even more strongly recommend you under all circumstances stay far away from the deprecated constructors and method of that outdated `Date` class. – Ole V.V. Dec 28 '19 at 21:52

3 Answers3

2

When you call Date(int year, int month, int date), The parameter should be like this:

@param   year    the year minus 1900.
@param   month   the month between 0-11.
@param   date    the day of the month between 1-31.

Since Date(int year, int month, int date) is deprecated, You can use Calendar and set like below to get desired date

Calendar calendar = Calendar.getInstance()
calendar.set(2019, Calendar.MARCH, 4)
Long timeInMillis = calendar.timeInMillis

// timeInMillis should be 1551718624170 equivalent to Mon Mar 04 2019
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
1

tl;dr

If you want to get the first moment of the day on that date as seen in UTC, transformed into a count of milliseconds since 1970-01-01T00:00Z :

LocalDate             // Represent a date, without time-of-day and without time zone.  
.of( 2019 , 3 , 4 )   // Determine a date. Uses sane numbering, 1-12 for January-December.
.atStartOfDay(        // Determine first moment of the day.
    ZoneOffset.UTC    // Get the first moment as seen at UTC (an offset of zero hours-minutes-days.
)                     // Returns a `ZonedDateTime` object.
.toInstant()          // Convert from a `ZonedDateTime` to a simple `Instant` object, which is always in UTC, and has methods to get count-from-epoch.
.toEpochMilli()       // Get a count of milliseconds since the epoch reference of first moment of 1970 to UTC.

java.time

You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.

To get a count of milliseconds or whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z, use Instant.

long millis = Instant.now().toEpochMilli() ;

Or:

long seconds = Instant.now().getEpochSecond() ;

For a date, you must determine the first moment of the day on that date. This not always the time 00:00, so let java.time determine that moment. Doing so requires a time zone. The day starts earlier in the East than in the west, varying around the globe by time zone.

LocalDate ld = LocalDate.of( 2019 , 3 , 4 ) ;
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
long millis = Instant.now().toEpochMilli() ;

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.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    @OleV.V. I altered your edit at top, changing your time zone to `ZoneOffset.UTC` as I was trying to show UTC up top and zoned down below. Thanks for that edit and the others. – Basil Bourque Dec 28 '19 at 22:36
  • Sorry, I had paid too little attention there. Thanks for reporting back. – Ole V.V. Dec 29 '19 at 05:58
0

Follow the JavaDoc of the Date method. It states that the value of the first argument year should be

the year minus 1900.

So the correct version of calling dateToTimestamp method would be

dateToTimestamp(new Date(119, 3, 4) .

This would give you 1554316200000. When Converted it would be 4th April 2019.

Note that the value of the month starts from 0 for January, 1 for February and so on.

Ajay Kr Choudhary
  • 1,304
  • 1
  • 14
  • 23