How to Parse Date String to Date

Parsing a string to a date in JavaScript

The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').

To display a date in UTC, use .toUTCString(),

to display a date in user's local time, use .toString().

More info on MDN | Date and this answer.

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.


Alternate method - use an appropriate library:

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

Java string to date conversion

That's the hard way, and those java.util.Date setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole java.util.Date class was de-facto deprecated (discommended) since introduction of java.time API in Java 8 (2014).

Simply format the date using DateTimeFormatter with a pattern matching the input string (the tutorial is available here).

In your specific case of "January 2, 2010" as the input string:

  1. "January" is the full text month, so use the MMMM pattern for it
  2. "2" is the short day-of-month, so use the d pattern for it.
  3. "2010" is the 4-digit year, so use the yyyy pattern for it.
String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter) instead of LocalDate#parse(text, formatter). And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter) instead.

Here's an extract of relevance from the javadoc, listing all available format patterns:

































































































































































































SymbolMeaningPresentationExamples
GeratextAD; Anno Domini; A
uyearyear2004; 04
yyear-of-erayear2004; 04
Dday-of-yearnumber189
M/Lmonth-of-yearnumber/text7; 07; Jul; July; J
dday-of-monthnumber10
Q/qquarter-of-yearnumber/text3; 03; Q3; 3rd quarter
Yweek-based-yearyear1996; 96
wweek-of-week-based-yearnumber27
Wweek-of-monthnumber4
Eday-of-weektextTue; Tuesday; T
e/clocalized day-of-weeknumber/text2; 02; Tue; Tuesday; T
Fweek-of-monthnumber3
aam-pm-of-daytextPM
hclock-hour-of-am-pm (1-12)number12
Khour-of-am-pm (0-11)number0
kclock-hour-of-am-pm (1-24)number0
Hhour-of-day (0-23)number0
mminute-of-hournumber30
ssecond-of-minutenumber55
Sfraction-of-secondfraction978
Amilli-of-daynumber1234
nnano-of-secondnumber987654321
Nnano-of-daynumber1234000000
Vtime-zone IDzone-idAmerica/Los_Angeles; Z; -08:30
ztime-zone namezone-namePacific Standard Time; PST
Olocalized zone-offsetoffset-OGMT+8; GMT+08:00; UTC-08:00;
Xzone-offset 'Z' for zerooffset-XZ; -08; -0830; -08:30; -083015; -08:30:15;
xzone-offsetoffset-x+0000; -08; -0830; -08:30; -083015; -08:30:15;
Zzone-offsetoffset-Z+0000; -0800; -08:00;

Python date string to date object

You can use strptime in the datetime package of Python:

>>> import datetime
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)

How to parse a date?

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

        String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);

...

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

How to parse date string to Date?

The pattern is wrong. You have a 3-letter day abbreviation, so it must be EEE. You have a 3-letter month abbreviation, so it must be MMM. As those day and month abbreviations are locale sensitive, you'd like to explicitly specify the SimpleDateFormat locale to English as well, otherwise it will use the platform default locale which may not be English per se.

public static void main(String[] args) throws Exception {
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date result = df.parse(target);
System.out.println(result);
}

This prints here

Thu Sep 28 07:29:30 BOT 2000

which is correct as per my timezone.

I would also reconsider if you wouldn't rather like to use HH instead of kk. Read the javadoc for details about valid patterns.

Parse string to DateTime in C#

DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact():

string s = "2011-03-21 13:26";

DateTime dt =
DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)

Make sure to check Custom Date and Time Format Strings when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).

Another useful resource for C# format strings is String Formatting in C#

Convert string to date then format the date

Use SimpleDateFormat#format(Date):

String start_dt = "2011-01-01";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD");
Date date = (Date)formatter.parse(start_dt);
SimpleDateFormat newFormat = new SimpleDateFormat("MM-dd-yyyy");
String finalString = newFormat.format(date);

Convert datetime object to a String of date only in Python

You can use strftime to help you format your date.

E.g.,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

will yield:

'02/23/2012'

More information about formatting see here

Convert String to Date with Milliseconds

The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.

You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.

If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:

System.out.println(formatter.format(dateFormatter));

outputs 2020-08-27T10:06:07.413



Related Topics



Leave a reply



Submit