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:
- "January" is the full text month, so use the
MMMM
pattern for it - "2" is the short day-of-month, so use the
d
pattern for it. - "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:
Symbol | Meaning | Presentation | Examples |
---|---|---|---|
G | era | text | AD; Anno Domini; A |
u | year | year | 2004; 04 |
y | year-of-era | year | 2004; 04 |
D | day-of-year | number | 189 |
M /L | month-of-year | number/text | 7; 07; Jul; July; J |
d | day-of-month | number | 10 |
Q /q | quarter-of-year | number/text | 3; 03; Q3; 3rd quarter |
Y | week-based-year | year | 1996; 96 |
w | week-of-week-based-year | number | 27 |
W | week-of-month | number | 4 |
E | day-of-week | text | Tue; Tuesday; T |
e /c | localized day-of-week | number/text | 2; 02; Tue; Tuesday; T |
F | week-of-month | number | 3 |
a | am-pm-of-day | text | PM |
h | clock-hour-of-am-pm (1-12) | number | 12 |
K | hour-of-am-pm (0-11) | number | 0 |
k | clock-hour-of-am-pm (1-24) | number | 0 |
H | hour-of-day (0-23) | number | 0 |
m | minute-of-hour | number | 30 |
s | second-of-minute | number | 55 |
S | fraction-of-second | fraction | 978 |
A | milli-of-day | number | 1234 |
n | nano-of-second | number | 987654321 |
N | nano-of-day | number | 1234000000 |
V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 |
z | time-zone name | zone-name | Pacific Standard Time; PST |
O | localized zone-offset | offset-O | GMT+8; GMT+08:00; UTC-08:00; |
X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; |
x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; |
Z | zone-offset | offset-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
Html5 Video Autoplay on Iphone
Nsdateformatter: Date According to Currentlocale, Without Year
Xcode6: Run Two Instances of the Simulator
How to Delay a Method Call for 1 Second
Get Current iPhone Device Timezone Date and Time from Utc-5 Timezone Date and Time iPhone App
iOS - Delayed "Touch Down" Event for Uibutton in Uitableviewcell
How to Write an Objective-C Completion Block
Startupdatelocations in Background, Didupdatingtolocation Only Called 10-20 Times
"Cannot Connect to Itunes Store" In-App Purchases
Swift: How to Execute an Action When Uitabbaritem Is Pressed
<Input Type="Number"/> Is Not Showing a Number Keypad on iOS
Catch an Exception for Invalid User Input in Swift
iOS Autolayout: Two Buttons of Equal Width, Side by Side
How to Remove an iOS App from the App Store
Iphone:How to Detect the End of Slider Drag