Converting String to Date Using Simpledateformat Is Returning Random Date

Converting String to Date using SimpleDateFormat is returning random date

You are using the format pattern string yyyyMMdd. You are parsing the date-time string 2018-06-20 00:00:00.

2018 matches yyyy. MM means that month should be two chars, so -0 is taken for the month. And -0 or just 0 is taken to be the month before month 1 of 2018, that is, December 2017. Finally 6 is taken as the day of month. It should have been two chars too, but since there is only one digit, SimpleDateFormat settles with that. The remainder of the string is tacitly ignored.

Exactly the same thing happens when parsing the other string.

It’s the long outdated SimpleDateFormat class in a nutshell: In its attempts to be friendly and helpful it produces the most unpleasant and confusing surprises. Where you would have wished it would tell you something is wrong, it just pretends that everything is fine. It’s one of the main reasons that this class is considered troublesome, and why the replacement for the old classes came out with Java 8 more than 4 years ago. So just never use SimpleDateFormat again.

Instead look into java.time and its DateTimeFormatter.

Also don’t get date values as strings from your database. Depending on the datatype that the query returns get either a LocalDateTime or a LocalDate object. This will free you completely from parsing.

Link: Oracle tutorial: Date Time explaining how to use java.time.

SimpleDateFormat adds random milliseconds while formatting to string

In the above output, everything is consistent except milliseconds
after dot(.), Can someone explain this?

The reason is that your format has milliseconds but you haven't set milliseconds in the Calendar instance; therefore, it gives you the milliseconds of the moment when you run your code.

You can verify the same using the following code:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.set(2020, 5, 22, 17, 30, 00);
Date date = calendar.getTime();

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String s = df.format(date);
System.out.println(s);
System.out.println(date.toInstant().getNano()); // Added this line
}
}

Output:

2020-06-22T17:30:00.425+0100
425000000

On a side note, I recommend you stop using outdated date-time API and start using the modern date-time API.

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = LocalDateTime.of(2020, 5, 22, 17, 30, 00).atZone(ZoneId.systemDefault());
System.out.println(zdt);
}
}

Java: return date format in random date

Use SimpleDateFormat

SimpleDateFormat formatter= new SimpleDateFormat("dd/MM/yyyy");
System.out.println(formatter.format(new Date(randomTimestamp)));

How to convert String to Date without knowing the format?

You cant!

If you have the date 2010-08-05 then it can be either 5th August 2010, or 8th May 2010 - you need to know the date format (or at least prioritise one format over the over) to tell them apart.

Reformat custom date from string

You are mixing up parsing and formatting: your code is trying to parse a string given the format. You’re telling Java you’re expecting the date to contain the week name.

You need to first parse your date in the format it’s in. This will give you a date. You next need format your date with the desired format, which will give you a string:

final String dateString = "2020-09-05";
final Date date = new SimpleDateFormat("y-M-d").parse(dateString);
final String converted = new SimpleDateFormat("E, d MMM y").format(date);

Parsing from String to Date throws Unparsable Date Error

Your target String format is in EEE MMM dd HH:mm:ss zzz yyyy format. So you need to use EEE MMM dd HH:mm:ss zzz yyyy as pattern instead of yyyy-MM-dd.

    String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
Date result = df.parse(target);
System.out.println(result);

And if you want convert Date object i.e result to yyyy-MM-dd then please use the below code.

    DateFormat dfDateToStr = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dfDateToStr.format(result);
System.out.println("Formatted Date String : "+formattedDate);

String to Date Conversion mm/dd/yy to YYYY-MM-DD in java

As you say the input is in a different format, first convert the String to a valid Date object. Once you have the Date object you can format it into different types , as you want, check.

To Convert as Date,

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
date = formatter.parse(dateVlaue);

To Print it out in the other format,

SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date)


Related Topics



Leave a reply



Submit