Java Parsing String to Date

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;

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 DateTime

You can create Joda DateTime object from the Java Date object, since Java does not have a DateTime class.

DateTime dt = new DateTime(start.getTime());

Though the Date class of Java holds the time information as well(that's what you need in the first place), I suggest you to use a Calendar instead of the Date class of Java.

Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

Have a look at the Calendar docs for more info on how you can use it more effectively.


Things have changed and now even Java (Java 8 to be precise), has a LocalDateTime and ZonedDateTime class. For conversions, you can have a look at this SO answer(posting an excerpt from there).

Given: Date date = [some date]

(1) LocalDateTime << Instant<< Date

Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

(2) Date << Instant << LocalDateTime

Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);

How can i convert String to Date when it has TRT in it

Where your code failed:

SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);

As you can see, the pattern of the SimpleDateFormat and that of the date string do not match and therefore, this code will throw ParseException.

How to make it work?

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);

You must have already got why it worked. It worked because the pattern of the SimpleDateFormat matches with that of the dateStr string.

Can I format the Date object (i.e. date) into the original string?

Yes, just use the same format which you used to parse the original string as shown below:

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);

// Display in the default format
System.out.println(date);

// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);

A piece of advice:

I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.

Using the modern date-time API:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);

// Display in the default format
System.out.println(date);

// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);

I don't see any difference using the legacy API and the modern API:

That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.

Demo:

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
public static void main(String[] args) {
// Given date-time string
String strDate = "Thu Aug 06 00:00:00 TRT 2020";

// Replace TRT with standard time-zone string
strDate = strDate.replace("TRT", "Europe/Istanbul");

// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");

// Parse the date-time string into ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
System.out.println(zdt);

// If you wish, convert ZonedDateTime into LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
}
}

Output:

2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00

Convert java.util.Date to String

Convert a Date to a String using DateFormat#format method:

String pattern = "MM/dd/yyyy HH:mm:ss";

// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);

// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);

// Print the result!
System.out.println("Today is: " + todayAsString);

From http://www.kodejava.org/examples/86.html

convert string to date without changing timezone in the string using java

Just omit the timezone format from the end of the String (letter Z).
For example, this will print Thu Nov 12 06:30:00 CET 2020

String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
var date = format.parse(s);
System.out.println(date);

But if I add the letter Z at the end, it will interpret the given timezone and change time to my local timezone, when printed. So this will print Thu Nov 12 15:30:00 CET 2020

String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
var date = format.parse(s);
System.out.println(date);

More about the patterns can be found in the JavaDoc of SimpleDateFormat.

Java Convert String and Long to DateTime

java.time

Quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.Instant;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;

LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);

Instant instant = Instant.ofEpochMilli(myLongDateAndTime);
System.out.println(instant);

OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-04:00"));
System.out.println(odt);

odt = odt.with(time);
System.out.println(odt);
}
}

Output:

12:30:10
2021-08-05T21:00:00Z
2021-08-05T17:00-04:00
2021-08-05T12:30:10-04:00

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Just for the sake of completeness

Just for the sake of completeness, given below is the solution using the Joda Date-Time API:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;

public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;

LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);

DateTime dateTime = new DateTime(Long.valueOf(myLongDateAndTime), DateTimeZone.forOffsetHours(-4));
System.out.println(dateTime);

dateTime = dateTime.withTime(time);
System.out.println(dateTime);
}
}

Output:

12:30:10.000
2021-08-05T17:00:00.000-04:00
2021-08-05T12:30:10.000-04:00

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.



Related Topics



Leave a reply



Submit