This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
Get Date type object in format in java
(6 answers)
convert java.util.Date to java.util.Date with different formating in JAVA [duplicate]
(1 answer)
Closed 11 months ago.
My requirement is to convert the string "2019-04-25 07:06:42.790" to Date Object with same format as "2019-04-25 07:06:42.790".
I tried to do this, but it is always giving in String format.
String createDate = "2019-04-25 07:06:42.790";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
LocalDateTime localDateTime = LocalDateTime.parse(createDate, formatter);
System.out.println(formatter.format(localDateTime));
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US);
formatter1.setTimeZone(TimeZone.getTimeZone("IST"));
Date date = formatter1.parse(createDate);
System.out.println(date);
String formattedDateString = formatter1.format(date);
System.out.println(formattedDateString);
Output from the above code:
2019-04-25 07:06:42.790
Thu Apr 25 07:06:42 IST 2019
2019-04-25 07:06:42.790
tl;dr
Date-time objects do not have a “format”.
Use only java.time classes.
LocalDateTime
.parse (
"2019-04-25 07:06:42.790"
.replace( " " , "T" )
)
.toString()
.replace( "T" , " " )
Details
You need to understand that date-time objects are not text. They don’t have a “format”. The do parse and generate text in various formats, but that text is always external.
Use only the java.time classes. Avoid legacy classes such as Date and Calendar.
Make your input comply with ISO 8601 standard.
String input = "2019-04-25 07:06:42.790".replace( " " , "T" ) ;
Parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse ( input ) ;
To generate the same text as your input, call toString and replace the T with your desired SPACE character.
You could use a DateTimeFormatter rather than the string manipulations shown above. But in your specific case I recommend the string manipulations.
Related
I have a date in the following format:
lastUpdatedDate = "12/14/2021 09:15:17";
I used the following code/format to convert date into yyyy-MM-dd hh:mm:ss format:
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
But it gives me below error:
java.text.ParseException: Unparseable date: "12/14/2021 09:15:17"
output should be: 2021-12-14 09:15:17
How can I achieve this?
Change the format to
SimpleDateFormat dt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
System.out.println(lastUpdatedDateFormatted);
And it should be able to parse the date then.
As you are wanting to display or output the date in yyyy-MM-dd HH:mm:ss format, you should parse the date first then format the date to desired format.
try {
String lastUpdatedDate = "12/14/2021 09:15:17";
Date lastDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(lastUpdatedDate);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lastDate));
} catch (ParseException e) {
e.printStackTrace();
}
Your formatting pattern fails to match your input string.
And you are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
The modern solution uses the java.time classes.
Your input lacks an indicator of time zone or offset from UTC, so parse as a LocalDateTime object.
LocalDateTime ldt =
LocalDateTime
.parse(
"12/14/2021 09:15:17" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss" ) ;
) ;
Your desired output is nearly compliant with the ISO 8601 standard format used by default in java.time, except for that SPACE in the middle rather than T.
String output = ldt.toString().replace( "T" , " " ) ;
This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 3 years ago.
Hi I am not able to understand what time format we need to use in order to parse this date2020-02-11T17:26:31-05:00 I have tried using Date formatter and simple date format but its not working
Date is coming in this form ->2020-02-11T17:26:31-05:00 I am not able to identify the type of this date
Below is snippet of code i have tried but its throwing exception
DateTimeFormatter responseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-SSSXXX'Z'",
Locale.ENGLISH);
responseDateTime = LocalDateTime.parse(otmmResponseDate, responseFormatter);
Notice that your date string has an offset -05:00 in it. Thus, your string does not represent a LocalDateTime, but an OffsetDateTime, and should be parsed by OffsetDateTime.parse (not everything is a LocalDateTime!):
// the format is ISO 8601, so it can be parsed directly without a DateTimeFormatter
OffsetDateTime odt = OffsetDateTime.parse("2020-02-11T17:26:31-05:00");
If you only want the local date time part of it, then you can call toLocalDateTime afterwards:
LocalDateTime ldt = odt.toLocalDateTime();
This is a datetime String that contains an offset of minus five hours. You don't even have to use a DateTimeFormatter directly, because parsing this to an OffsetDateTime will do:
public static void main(String[] args) {
String dateString = "2020-02-11T17:26:31-05:00";
OffsetDateTime odt = OffsetDateTime.parse(dateString);
System.out.println(odt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}
Output:
2020-02-11T17:26:31
Not that this uses a DateTimeFormatter without an offset for the output.
This question already has answers here:
Java string to date conversion
(17 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Change date format in a Java string
(22 answers)
Convert java.util.Date to String
(17 answers)
Closed 3 years ago.
I am trying the code
Date today = new Date();
Date todayWithZeroTime;
{
try {
todayWithZeroTime = formatter.parse(formatter.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
}
String date = todayWithZeroTime.toString();
it is giving output :- Wed Dec 11 00:00:00 IST 2019
where I want 11/12/2019
where 11/12/2019 is today's date
Using java.time.LocalDate,
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
Use DateTimeFormatter to format the date as you want.
In your case the pattern is "dd/MM/yyyy".
Info ⬇️
Java 8 introduced new APIs for Date and Time to address the shortcomings of the older java.util.Date and java.util.Calendar. The core classes of the new Java 8 project that are part of the java.time package like LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration and their supported APIs.
The LocalDate provides various utility methods to obtain a variety of information. For example:
1) The following code snippet gets the current local date and adds one day:
LocalDate tomorrow = LocalDate.now().plusDays(1);
2) This example obtains the current date and subtracts one month. Note how it accepts an enum as the time unit:
LocalDate previousMonthSameDay = LocalDate.now().minus(1, ChronoUnit.MONTHS);
If you are using JAVA 8 you can use LocalDateTime class and DateTimeFormatter.
see below example using JAVA 8:
LocalDateTime now = LocalDateTime.now();
System.out.println("Current DateTime Before Formatting: " + now);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formatedDateTime = now.format(formatter);
System.out.println("Current DateTime after Formatting:: " + formatedDateTime );
I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
My Question is, how to tweak this code so it will work for below scenarios ex,
my s string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
right now it fails if I don't pass the ms.. Thanks!
Different types
String s = "2019-04-23 06:57:00";
String s = "2019-04-23";
These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.
LocalDateTime.parse
To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.
LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
The fractional second parses by default as well.
LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
See this code run live at IdeOne.com.
ldt1.toString(): 2019-04-23T06:57
ldt2.toString(): 2019-04-23T06:57
LocalDate.parse
Your date-only input already complies with ISO 8601.
LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-04-23
Date with time-of-day
You can strip out the time-of-day from the date.
LocalDate ld = ldt.toLocalDate() ;
And you can add it back in.
LocalTime lt = LocalTime.parse( "06:57:00" ) ;
LocalDateTime ldt = ld.with( lt ) ;
Moment
However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.
For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.
Avoid legacy date-time classes
The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.
In case of you have optional parts in pattern you can use [ and ].
For example
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS
I have a date string in this format:
String fieldAsString = "11/26/2011 14:47:31";
I am trying to convert it to a Date type object in this format: "yyyy.MM.dd HH:mm:ss"
I tried using the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date newFormat = sdf.parse(fieldAsString);
However, this throws an exception that it is an Unparsable date.
So I tried something like this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
String newFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date)
However, this new format is now in the 'String' format but I want my function to return the new formatted date as a 'Date' object type. How would I do this?
Thanks!
You seem to be under the impression that a Date object has a format. It doesn't. It sounds like you just need this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
(You should consider specifying a locale and possibly a time zone, mind you.)
Then you've got your Date value. A format is only relevant when you later want to convert it to text... that's when you should specify the format. It's important to separate the value being represent (an instant in time, in this case) from a potential textual representation. It's like integers - there's no difference between these two values:
int x = 0x10;
int y = 16;
They're the same value, just represented differently in source code.
Additionally consider using Joda Time for all your date/time work - it's a much cleaner API than java.util.*.
The answer by Jon Skeet is correct and complete.
Internal to java.util.Date (and Date-Time seen below), the date-time value is stored as milliseconds since the Unix epoch. There is no String inside! When you need a textual representation of the date-time in a format readable by a human, either call toString or use a formatter object to create a String object. Likewise when parsing, the input string is thrown away, not stored inside the Date object (or DateTime object in Joda-Time).
Joda-Time
For fun, here is the (better) way to do this work with Joda-Time, as mentioned by Mr. Skeet.
One major difference is that while a java.util.Date class seems to have a time zone, it does not. A Joda-Time DateTime in contrast does truly know its own time zone.
String input = "11/26/2011 14:47:31";
// From text to date-time.
DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Time zone intended but unrecorded by the input string.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" ).withZone( timeZone );
// No words in the input, so no need for a specific Locale.
DateTime dateTime = formatterInput.parseDateTime( input );
// From date-time to text.
DateTimeFormatter formatterOutput_MontréalEnFrançais = DateTimeFormat.forStyle( "FS" ).withLocale( java.util.Locale.CANADA_FRENCH ).withZone( DateTimeZone.forID( "America/Montreal" ) );
String output = formatterOutput_MontréalEnFrançais.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime as milliseconds since Unix epoch: " + dateTime.getMillis() );
System.out.println( "dateTime in UTC: " + dateTime.withZone( DateTimeZone.UTC ) );
System.out.println( "output: " + output );
When run…
input: 11/26/2011 14:47:31
dateTime: 2011-11-26T14:47:31.000-10:00
dateTime as milliseconds since Unix epoch: 1322354851000
dateTime in UTC: 2011-11-27T00:47:31.000Z
output: samedi 26 novembre 2011 19:47
Search StackOverflow for "joda" to find many more examples.