Java Date() Giving the Wrong Date

Java Date() giving the wrong date

DD means Day of Year, while dd means Day of Month. Also, Y means Week Year, while y means Year. You want yyyy-MM-dd (case-sensitive).

public String getDate(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();

return dateFormat.format(date);
}

SimpleDateFormat parsing wrong date

tl;dr

myJavaUtilDate 
.toInstant()
.atZone
(
ZoneId.of( "Asia/Kolkata" )
)
.toLocalDate()
.isEqual
(
LocalDate
.parse
(
"03/10/2020" , // Do you mean March 10th, or October 3rd?
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Or "MM/dd/uuuu".
)
)

Smart objects, not dumb strings

You said:

make 3 dates of the same format so that I can compare them

Use objects with comparison methods, rather than comparing text of strings.

We have a class for dates built into Java: LocalDate.

java.time

You are using Date which is one of the terrible date-time classes bundled with the earliest versions of Java. These classes are now obsolete, supplanted years ago with the adoption of JSR 310 that defines the java.time classes.

I have passed a date

When encountering a java.util.Date object, immediately convert to its modern replacement, java.time.Instant. Use the new conversion method toInstant added to the old class.

Instant instant = myJavaUtilDate.toInstant() ;

Both java.util.Date and java.time.Instant represent a moment in UTC. Is that how you want to perceive the date, in UTC with an offset of zero hours-minutes-seconds from the prime meridian? Keep in mind that for any given moment the date varies around the globe by zone. A moment may be "tomorrow" in Tokyo Japan while still "yesterday" in Toledo Ohio US.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

Extract the date.

LocalDate ld = odt.toLocalDate() ;  // Extract the date only, omitting the time-of-day and the offset-from-UTC.

Or did you want to perceive that date in a particular zone?

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
LocalDate ld = zdt.toLocalDate() ; // Extract the date only, omitting the time-of-day and the zone.

and two string to a function

Define a formatting pattern to match your inputs.

String input = "03/10/2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ; // Throws `DateTimeParseException` if input is faulty.

Now compare, using methods isEqual, isAfter, isBefore.

boolean datesMatch = ld1.isEqual( ld2 ) && ld2.isEqual( ld3 ) ;

java.util.Date::toString tells a lie

You asked:

D2 = sat Oct 03 00:00:00 IST 2020 //wrong date fdate was 03/10/2020

Can anyone tell where did I go wrong?

Your main problem is that your formatting pattern is not defined to match your intention. This is correctly identified in the Answer by Chris and the Answer by Arvind Kumar Avinash.

In addition, you have another issue. Among the many problems with java.util.Date is that its toString method on-the-fly applies the JVM’s current default time zone while generating text to represent the content of the object. This creates the illusion of that zone being stored within the object. When perceiving your Date object’s UTC value after adjusting to a time zone, the date may differ from the date as seen in UTC. This was discussed above.

➥ Never use java.util.Date.


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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Simple date format giving wrong time

In your example, you are using time 1618274313 and you are assuming that it is in milliseconds. However, when I entered the same time on https://www.epochconverter.com/, I got below results:

Please notice the site mentions: Assuming that this timestamp is in seconds.


Now if we use that number multiplied by 1000 (1618274313000) as the input so that the site considers it in milliseconds, we get below results:

Please notice the site now mentions: Assuming that this timestamp is in milliseconds.


Now, when you will use 1618274313000 (correct time in milliseconds) in Java with SimpleDateFormat, you should get your expected result (instead of 23:01:14):

SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313000)));

Converting date to timestamp returns the wrong date

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

java.util.Date is generating a wrong date?

What may be the reason behind this Wrong Output ?

Your assumptions about the date format string are wrong, the output is correct.

y   Year
Y Week year
D Day in year
d Day in month
M Month in year
m Minute in hour

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Y Week year will usually give incorrect results around new year. D will give incorrect results from February. So your format appeared fine most of last month.

@DateTimeFormat in Spring gives wrong date

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

A java.util.Date object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, it is the JVM's timezone that gets applied by default while parsing/formatting using SimeplDateFormat, which could be the root cause of the problem in your case.

Solution using java.time, the modern Date-Time API: Change the type of date field to LocalDate as follows:

public static void exampleMethod(
@ApiParam(value = "date", required = true)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {...}

Learn more about the modern Date-Time API from Trail: Date Time.

In case you want to use java.util.Date:

As per the documentation:

Whenever the iso() attribute is used when formatting Date values, UTC
will be used as the time zone.

So, all you need to do is to use iso() attribute i.e.

public static void exampleMethod(
@ApiParam(value = "date", required = true)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date) {...}

* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

Simple Date format returns Wrong date intermittently

I'm sure that if you don't use that static instance of SimpleDateFormat you will have no problem:

public static String getCurrentDateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = new Date();
String datetime = sdf.format(d);
return datetime;
}

See these links:

Why is Java's SimpleDateFormat not thread-safe?

"Java DateFormat is not threadsafe" what does this leads to?

SimpleDateFormat with Calendar giving wrong date

Replace

val myFormat = "dd/MM/YYYY HH:mm:ss"

To

val myFormat = "dd/MM/yyyy HH:mm:ss"

Date Conversion returns wrong date when converted into timestamps

Same problem occurred and my solution was i have converted datetime into toLocalString.

var dateTime = new Date();
var sendObj = dateTime.now().toLocalString();

UPDATE:

dob = "15-05-2001";
dob = new Date(moment(this.dob, "dd-MM-YYYY").format()).getTime();


Related Topics



Leave a reply



Submit