I have to parse a date string (e.g. "October 2015") to a Date.
So the question is: how can I parse a date of MMMM yyyy format? Its ok if the new Date object is the first month of the given month.
I tried:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM yyyy").toFormatter();
TemporalAccessor ta = formatter.parse(node.textValue());
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
But it does not work since the day is missing.
What you have there is a YearMonth, not a LocalDate since the day is missing.
The following works:
String string = "October 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
YearMonth yearMonth = YearMonth.parse(string, formatter);
// Alternatively: YearMonth yearMonth = formatter.parse(string, YearMonth::from);
LocalDate date = yearMonth.atDay(1);
System.out.println(yearMonth); // prints "2015-10"
System.out.println(date); // prints "2015-10-01"
If you then want that as a java.util.Date, you need to specify which time zone you mean, maybe UTC or system default?
// ZoneId zone = ZoneOffset.UTC;
ZoneId zone = ZoneId.systemDefault();
Date javaUtilDate = Date.from(date.atStartOfDay(zone).toInstant());
System.out.println(javaUtilDate); // prints "Thu Oct 01 00:00:00 CEST 2015"
// because i'm in Europe/Stockholm.
How about this
DateFormat format = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
Date date = format.parse("October 2015");
System.out.println(date); // Prints Thu Oct 01 00:00:00 BST 2015
For java 8
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("MMMM yyyy")
.toFormatter(Locale.US);
TemporalAccessor ta = formatter.parse("October 2015");
YearMonth ym = YearMonth.from(ta);
LocalDateTime dt = LocalDateTime.of(ym.getYear(), ym.getMonthValue(),
1, 0, 0, 0);
Instant instant = Instant.from(dt.atZone(ZoneId.systemDefault()));
Date d = Date.from(instant);
You can use SimpleDateFormat's parse method for that
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMMMM yyyy"); //MMMM yyyy example: October 2015
public Date getDateFromString(String input) {
return DATE_FORMAT.parse(input);
}
For more information, see: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)
Explanation of format:
MMMM indicates you are parsing full name months such as "October"
yyyy indicates you have 4-digit length years. If you wanted to parse for example, October 15, your format would look like this: "MMMM yy"
Why not use a SimpleDateFormatter?
This works fine for me:
SimpleDateFormat formatter = new SimpleDateFormat("MMMM yyyy");
Date d = formatter.parse("Oktober 2015");
Related
How to convert date format "2021-02-28 13:38:00.597+0000" to "Mon, Feb 28,2021 15:25:00 UTC" UTC format in Scala?
If you are using an older Java version prior to Java 8, it's best to use the DateTimeFormat from joda-time. BTW, the +0000 zone offset is for UTC, so I could have omitted withZoneUTC(), but I still used it for the first date just to be safe:
val oldDateString = "2021-02-28 13:38:00.597+0000"
val OldFormat = "yyyy-MM-dd HH:mm:ss.SSSZ"
val NewFormat = "EEE, MMM dd, yyyy HH:mm:ss z"
val formatterOld = DateTimeFormat.forPattern(OldFormat)
val formatterNew = DateTimeFormat.forPattern(NewFormat)
val dt = formatterOld.withZoneUTC().parseDateTime(oldDateString)
val dateStringInUTC = formatterNew.withZoneUTC().print(dt)
println(dt) // 2021-02-28T13:38:00.597Z
println(dateStringInUTC) // Sun, Feb 28, 2021 13:38:00 UTC
UPDATE: For Java 8 and newer, the java.time API is your friend. Similarly, withZoneSameInstant(ZoneOffset.UTC) was not really needed:
val oldDateString = "2021-02-28 13:38:00.597+0000"
val OldFormat = "yyyy-MM-dd HH:mm:ss.SSSZZZ"
val NewFormat = "EEE, MMM dd, yyyy HH:mm:ss z"
val formatterOld = DateTimeFormatter.ofPattern(OldFormat)
val formatterNew = DateTimeFormatter.ofPattern(NewFormat)
val zdt = ZonedDateTime.parse(oldDateString, formatterOld)
val dateStringInUTC = zdt.withZoneSameInstant(ZoneId.of("UTC")).format(formatterNew)
println(zdt) // 2021-02-28T13:38:00.597Z
println(dateStringInUTC) // Sun, Feb 28, 2021 13:38:00 UTC
UPDATE: Switched to using ZoneId.of("UTC") instead of ZoneOffset.UTC because the latter does not get the String UTC printed at the end, even though ZoneOffset extends ZoneId, as #deHaar mentioned.
If you could use java.time, you would need
a DateTimeFormatter for parsing Strings with the format of your input example, which is quite near to ISO standard, but is missing the 'T' between date and time of day
another DateTimeFormatter for outputting the temporal content in the desired format, which includes (English) abbreviations for day of week and month of year
an OffsetDateTime for parsing the String with the first DateTimeFormatter and
a ZonedDateTime for the temporal value in UTC
This is how I would do it in Java:
public static void main(String[] args) {
// example String
String utcDatetimeString = "2021-02-28 13:38:00.597+0000";
// prepare a formatter that can parse a String of this format
DateTimeFormatter dtfIn = DateTimeFormatter.ofPattern(
"uuuu-MM-dd HH:mm:ss.SSSxxxx",
Locale.ENGLISH
);
// parse it to an OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(utcDatetimeString, dtfIn);
// then convert it to a ZonedDateTime applying UTC zone
ZonedDateTime zdt = odt.atZoneSameInstant(ZoneId.of("UTC"));
// prepare a formatter that produces the desired output
DateTimeFormatter dtfOut = DateTimeFormatter.ofPattern(
"EEE, MMM dd, uuuu HH:mm:ss zzz",
Locale.ENGLISH
);
// and print the ZonedDateTime using the formatter
System.out.println(zdt.format(dtfOut));
}
Output:
Sun, Feb 28, 2021 13:38:00 UTC
My frontend ReactJs code snippet:-
import React, { useState } from 'react';
import DateTimePicker from 'react-datetime-picker';
import './App.css';
function App() {
const [value, onChange] = useState(new Date());
console.log("onChage: "+value);
return (
<div className="App">
<DateTimePicker
onChange={onChange}
value={value}
format={'dd/mm/yyyy hh:mm'}
/>
</div>
);
}
export default App;
I can see console log as
onChage: Thu Jul 21 2022 13:11:32 GMT+0300 (Eastern European Summer
Time)
I need to send this date time to Java Spingboot backend. For the backend I need to convert this date time to OffsetDateTime or LocalDateTime. How can I convert this?
Updated:
I tried and managed to convert to Data. By this:-
String dateStr = "Thu Jul 21 2022 13:11:32 GMT+0300 (Eastern European Summer Time)";
String[] tokens = dateStr.split("GMT");
String dateTimeStr = "";
if (tokens.length == 2){
dateTimeStr = tokens[0].trim();
}
System.out.println(dateTimeStr);
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
Date date = formatter.parse(dateTimeStr);
String formattedDateString = formatter.format(date);
System.out.println("date: "+formattedDateString);
There I lost time zone and offset. How do I keep the time zone and offset GMT+0300 (Eastern European Summer Time)?
After the comment by Ole V.V. I mangaged to get both OffsetDateTime and ZonedDateTime. I am sharing the soluion. All credit goes to Ole V.V. Thanks a lot Ole V.V.
String dateStr = "Thu Jul 21 2022 13:11:32 GMT+0300 (Eastern European Summer Time)";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEE MMM d yyyy HH:mm:ss 'GMT'XX (zzzz)", Locale.ROOT);
OffsetDateTime date1 = OffsetDateTime.parse(dateStr, dateTimeFormatter);
System.out.println(date1);
// print 2022-07-21T13:11:32+03:00
ZonedDateTime zdt = ZonedDateTime.parse(dateStr, dateTimeFormatter.withZone(ZoneId.systemDefault()));
System.out.println(zdt);
// print 2022-07-21T13:11:32+03:00[Europe/Bucharest]
Simplest way to do is just do this :-
String timeString = input.substring(4,24);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd YYYY HH:mm:ss");
System.out.println(LocalDateTime.parse(timeString, formatter);
This question might sound similar to most of the other questions asked here on Stackoverflow but I could not figure out my problem.
I want to parse the string value into a date.
String dateTime = "23 Oct 2020 02:44:58 +1000"
The solution to this problem is:
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseCaseInsensitive();
builder.appendPattern("d MMM yyyy HH:mm[:ss] Z");
DateTimeFormatter dtf = builder.toFormatter();
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTime, dtf);
Instant instant = zonedDateTime.toInstant();
Date finalDate = Date.from(instant);
If I want to parse the date with timezone instead like String dateTime = "23 Oct 2020 02:44:58 AEST" then I need to change the builder.appendPattern("d MMM yyyy HH:mm[:ss] Z"); from capital Z to small z as mentioned here.
The question here is how would I make my parser flexible enough for it to handle either timezone or offset value?
Note. I have used [ss] as the seconds' field is optional. And as per documentation using VV was similar to z while 'V' did not work for me.
You can add them as optional parts to the formatter, just like you did with the seconds part:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d MMM yyyy HH:mm[:ss] [Z][z]")
.toFormatter(Locale.ROOT);
Online demo
[ and ] denote an optional part: the corresponding text is consumed if it can be successfully parsed by means of the pattern within the brackets, otherwise, no text is consumed and the pattern within is skipped.
You can try using try-catch block
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseCaseInsensitive();
builder.appendPattern("d MMM yyyy HH:mm[:ss] Z");
DateTimeFormatter dtf = builder.toFormatter();
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseCaseInsensitive();
builder.appendPattern("d MMM yyyy HH:mm[:ss] z");
DateTimeFormatter dtf = builder.toFormatter();
ZonedDateTime zonedDateTime;
try {
zonedDateTime = ZonedDateTime.parse(dateTime, dtf1);
} catch (DateTimeParseException e) {
zonedDateTime = ZonedDateTime.parse(dateTime, dtf2);
}
Instant instant = zonedDateTime.toInstant();
Date finalDate = Date.from(instant);
I have a date-time from Los_Angeles. The daylight saving applies when possible. I'm trying to convert that date-time into a timestamp, but I don't seem to understand the Java 8 DateTime API. The following snippet returns 1238112000 (which is the correct date if it was specified in UTC). What should I change to show 1238137200 instead?
String date = "March 27, 2009 00:00:00";
DateTimeFormatter formatter = DateTimeFormatter.
ofPattern("MMMM dd, yyyy HH:mm:ss", Locale.ENGLISH).
withZone(ZoneId.of("America/Los_Angeles"));
LocalDateTime.parse(date, formatter).toEpochSecond(ZoneOffset.UTC))
By parsing the date into a LocalDateTime, you are ignoring the timezone information from the formatter. You should use a ZonedDateTime:
public static void main(String[] args) {
String date = "March 27, 2009 00:00:00";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMMM dd, yyyy HH:mm:ss", Locale.ENGLISH)
.withZone(ZoneId.of("America/Los_Angeles"));
long second = ZonedDateTime.parse(date, formatter).toEpochSecond();
System.out.println(second); // prints "1238137200"
}
On the returned instance, you can then call toEpochSecond().
"Mar 10, 2016 6:30:00 PM" This is my date and I want to convert this into "10 Mar 2016". Can I use SimpleDateFormat in android. I am not getting the exact pattern to convert it. Please help and thanks in advance
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("Some Pattern for above date");
Date newDate=spf.format(date);
spf= new SimpleDateFormat("dd MMM yyyy");
String date = spf.format(newDate);
Will this steps work? If yes, can someone please give me a pattern of that format? Thanks in advance.
This is modified code that you should use:
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);
Use hh for hours in order to get correct time.
Java 8 and later
Java 8 introduced new classes for time manipulation, so use following code in such cases:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(dateTime.format(formatter2));
Use h for hour format, since in this case hour has only one digit.
conversion from string to date and date to string
String deliveryDate="2018-09-04";
SimpleDateFormat dateFormatprev = new SimpleDateFormat("yyyy-MM-dd");
Date d = dateFormatprev.parse(deliveryDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM yyyy");
String changedDate = dateFormat.format(d);
You can use following method for this problem. We simply need to pass Current date format, required date format and Date String.
private String changeDateFormat(String currentFormat,String requiredFormat,String dateString){
String result="";
if (Strings.isNullOrEmpty(dateString)){
return result;
}
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date=null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}
This method will return Date String in format you require.
In your case method call will be:
String date = changeDateFormat("MMM dd, yyyy hh:mm:ss a","dd MMM yyyy","Mar 10, 2016 6:30:00 PM");
You should parse() the String into Date and then format it into the desired format. You can use MMM dd, yyyy HH:mm:ss a format to parse the given String.
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String date = "Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Date newDate = spf.parse(date);
spf = new SimpleDateFormat("dd MMM yyyy");
String newDateString = spf.format(newDate);
System.out.println(newDateString);
}
Output:
10 Mar 2016
For the sake of completeness, here is the modern version. This is for anyone reading this who either uses Java 8 or later or is happy with a (good and futureproof) external library.
String date = "Mar 10, 2016 6:30:00 PM";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("MMM d, uuuu h:mm:ss a", Locale.ENGLISH);
DateTimeFormatter newFormatter
= DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH);
date = LocalDateTime.parse(date, parseFormatter).format(newFormatter);
System.out.println(date);
This prints the desired
10 Mar 2016
Please note the use of explicit locale for both DateTimeFormatter objects. “Mar” and “PM” both are in English, so neither the parsing nor the formatting will work unless some English-speaking locale is used. By giving it explicitly we are making the code robust enough to behave as expected also on computers and JVMs with other default locales.
To use the above on Android, use ThreeTenABP, please see How to use ThreeTenABP in Android Project. On other Java 6 and 7 use ThreeTen Backport.
You need to use SimpleDateFormat class to do the needful for you
String date = "Your input date"
DateFormat originalFormat = new SimpleDateFormat("<Your Input format here>", Locale.US)
DateFormat targetFormat = new SimpleDateFormat("<Your desired format here>", Locale.US)
Date Fdate = originalFormat.parse(date)
formattedDate = targetFormat.format(Fdate)
public static String formatDate(String fromFormat, String toFormat, String dateToFormat) {
SimpleDateFormat inFormat = new SimpleDateFormat(fromFormat);
Date date = null;
try {
date = inFormat.parse(dateToFormat);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outFormat = new SimpleDateFormat(toFormat);
return outFormat.format(date);
}
Use:
formatDate("dd-MM-yyyy", "EEEE, dd MMMM yyyy","26-07-2019");
Result:
Friday, 26 July 2019