How to Parse a Date

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

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.

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.

How to parse a date and only the date from a `date_string` in python?

Simply call .date() on the datetime object. This returns a date object.

In [5]: dt
Out[5]: datetime.datetime(2010, 7, 1, 0, 0)
In [6]: dt.date()
Out[6]: datetime.date(2010, 7, 1)

For your other subquestions:

  • Yes, the 0, 0 is the time.
  • A date always has year, month and day (with 1 <= day <= 31).

Fastest way to parse a YYYYMMdd date in Java

As you see below, the performance of the date processing only is relevant when you look at millions of iterations. Instead, you should choose a solution that is easy to read and maintain.

Although you could use SimpleDateFormat, it is not reentrant so should be avoided. The best solution is to use the great Joda time classes:

private static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()
.appendYear(4,4).appendMonthOfYear(2).appendDayOfMonth(2).toFormatter();
...
Date date = DATE_FORMATTER.parseDateTime(dateOfBirth).toDate();

If we are talking about your math functions, the first thing to point out is that there were bugs in your math code that I've fixed. That's the problem with doing by hand. That said, the ones that process the string once will be the fastest. A quick test run shows that:

year = Integer.parseInt(dateString.substring(0, 4));
month = Integer.parseInt(dateString.substring(4, 6));
day = Integer.parseInt(dateString.substring(6));

Takes ~800ms while:

int date = Integer.parseInt(dateString);
year = date / 10000;
month = (date % 10000) / 100;
day = date % 100;
total += year + month + day;

Takes ~400ms.

However ... again... you need to take into account that this is after 10 million iterations. This is a perfect example of premature optimization. I'd choose the one that is the most readable and the easiest to maintain. That's why the Joda time answer is the best.

How do you parse a date from an HTML5 date input?

It's interpreting the date as UTC, which, for most time zones, will make it seem like "yesterday". One solution could be to add the time-zone offset back into the date to "convert" it to your local timezone.

How do I convert date class to parse date time correctly?

Try it like this. But use the methods in the java.time package. It is superior in many ways to the java.util.Date and supported methods which are outmoded (and quite a few are deprecated).

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
OffsetDateTime odt = OffsetDateTime.parse("1995-01-28T17:02:12.936000-0500",dtf);
DateTimeFormatter resultFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(odt.format(resultFormat));

Prints

1995-01-28 17:02:12


Related Topics



Leave a reply



Submit