Getting Back a Date from a String

Getting back a date from a string

The problem there is that Y is for weekOfYear. You have to use "dd-MM-yyyy". Btw don't forget to set your date formatter locale to "en_US_POSIX" .

If you're working with fixed-format dates, you
should first set the locale of the date formatter to something
appropriate for your fixed format. In most cases the best locale to
choose is "en_US_POSIX", a locale that's specifically designed to
yield US English results regardless of both user and system
preferences. "en_US_POSIX" is also invariant in time (if the US, at
some point in the future, changes the way it formats dates, "en_US"
will change to reflect the new behaviour, but "en_US_POSIX" will not),
and between machines ("en_US_POSIX" works the same on iOS as it does
on OS X, and as it it does on other platforms).

How to extract a date from a string and put it into a date variable in Java

For this, a regular expression is your friend:

String input = "John Doe at:2016-01-16 Notes:This is a test";

String regex = " at:(\\d{4}-\\d{2}-\\d{2}) Notes:";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find()) {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(m.group(1));
// Use date here
} else {
// Bad input
}

Or in Java 8+:

    LocalDate date = LocalDate.parse(m.group(1));

converting date to string and back to date in java

when i convert the string back to date using parse(), it is changing to Wed May 23 13:16:14 IST 2012.

That is not true, It converts back to Date correctly, When you try to print Date instance, It invokes toString() method and it has fixed formated output so if you want the formatted date you need to use format() method

In short parse method parses the String to Date there is no property of Date which holds format so you need to use format() method anyhow

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;

rails convert a string back to date format

Date.parse("17 Aug")
# Sun, 17 Aug 2014

You may want to bring everything to the same year for the comparison to be effective, just to make sure.

bday = Date.parse("#{student.bday} #{Date.today.strftime('%Y')}")

But default behaviour is to add current year, so this is just redundant...

Better still, provide a parse model, for parsing to be most accurate

bday = Date.strptime("#{student.bday} #{Date.today.strftime('%Y')}",'%d %b %Y')
# %d: day of month, %b: Short month, %Y: Year


Related Topics



Leave a reply



Submit