Changing String Date Format

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

Convert String Date to String date different format

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("2013-02-21");
System.out.println(format2.format(date));

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);

How to convert String to Date with a specific format in java

The class Date will always contain both date a nd time information, since it represents an instant in time.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParsingDate {

public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d;
try {
d = fmt.parse("04-12-2019");
System.out.println(d); // Wed Dec 04 00:00:00 CET 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}

As you can see, hours, minutes, seconds and millis get all set to 0.

If you later want to output the date in string format, you need to use the DateFormat#format(Date) method:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParsingDate {

public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d = new Date();
System.out.println(d); // Wed Dec 04 11:24:35 CET 2019
System.out.println(fmt.format(d)); // 04-12-2019
}
}

If you'd rather store only date information, you could use the java.time package and make use of LocalDate.

LocalDate stores only date information, since it does not represent an instant, rather a triple of year, month and date.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class ParsingLocalDate {

public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("04-12-2019", fmt);
System.out.println(d); // 2019-12-04
}
}

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;

Convert string into date format in R

The as.Date() function will convert a string into date format, and the format of the output will always be in yyyy-mm-dd format in R (ISO 8601). The format argument in the as.Date() function is to specify the date format of the string input. I remember I initially thought it was specifying the output format, but it's the input format (you can change the output format with a subsequent format() function, however this will convert it back to a string).

Your string looks to be in ddmmyyyy (%d%m%Y) format, this should be what you specify as the format argument in as.Date(). Your format does not include hyphens, so the format argument should also not include hyphens. Note that ddmmyyyy, dd-mm-yyyy, dd/mm/yyyy, dd.mm.yyyy are all different date formats, even though the day, month and year are in the same order, they would be converted to date with formats %d%m%Y, %d-%m-%Y, %d/%m/%Y, and %d.%m.%Y, respectively.

Further advice on working with dates and times is available in the relevant chapters of R for Data Science by Wickham & Grolemund and The R Cookbook by Teetor & Long.

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.



Related Topics



Leave a reply



Submit