How to convert String to Date – Java?

In this tutorial, we will show you how to convert a String to java.util.Date. Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways.

    // String -> Date
    SimpleDateFormat.parse(String);

    // Date -> String
    SimpleDateFormat.format(date);

Refer to table below for some of the common date and time patterns used in java.text.SimpleDateFormat, refer to this JavaDoc

LetterDescriptionExamples
yYear2013
MMonth in yearJuly, 07, 7
dDay in month1-31
EDay name in weekFriday, Sunday
aAm/pm markerAM, PM
HHour in day0-23
hHour in am/pm1-12
mMinute in hour0-60
sSecond in minute0-60

Note
You may interest at this Java 8 example – How to convert String to LocalDate

1. String = 7-Jun-2013

If 3 ‘M’, then the month is interpreted as text (Mon-Dec), else number (01-12).TestDateExample1.java

package com.mkyong.date;

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

public class TestDateExample1 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        String dateInString = "7-Jun-2013";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 00:00:00 MYT 2013
07-Jun-2013

2. String = 07/06/2013

TestDateExample2.java

package com.mkyong.date;

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

public class TestDateExample2 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String dateInString = "07/06/2013";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 00:00:00 MYT 2013
07/06/2013

3. String = Fri, June 7 2013

TestDateExample3.java

package com.mkyong.date;

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

public class TestDateExample3 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
        String dateInString = "Fri, June 7 2013";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 00:00:00 MYT 2013
Fri, Jun 07 2013

4. String = Friday, Jun 7, 2013 12:10:56 PM

TestDateExample4.java

package com.mkyong.date;

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

public class TestDateExample4 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
        String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 12:10:56 MYT 2013
Friday, Jun 07, 2013 12:10:56 PM

5. String = 2014-10-05T15:23:01Z

Z suffix means UTC, java.util.SimpleDateFormat doesn’t parse it correctly, you need to replace the suffix Z with ‘+0000’.TestDateExample5.java

package com.mkyong.date;

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

public class TestDateExample5 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String dateInString = "2014-10-05T15:23:01Z";

        try {

            Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
            System.out.println(date);

            System.out.println("time zone : " + TimeZone.getDefault().getID());
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Sun Oct 05 23:23:01 MYT 2014
time zone : Asia/Kuala_Lumpur
2014-10-05T23:23:01+0800

In Java 8, you can convert it into a java.time.Instant object, and display it with a specified time zone.TestDateExample6.java

package com.mkyong.date;

import java.time.*;

public class TestDateExample6 {

    public static void main(String[] argv) {

        String dateInString = "2014-10-05T15:23:01Z";

        Instant instant = Instant.parse(dateInString);

        System.out.println(instant);

        //get date time only
        LocalDateTime result = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneOffset.UTC.getId()));

        System.out.println(result);

        //get date time + timezone
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Africa/Tripoli"));
        System.out.println(zonedDateTime);

        //get date time + timezone
        ZonedDateTime zonedDateTime2 = instant.atZone(ZoneId.of("Europe/Athens"));
        System.out.println(zonedDateTime2);
        
    }

}

Output

2014-10-05T15:23:01Z
2014-10-05T15:23:01
2014-10-05T17:23:01+02:00[Africa/Tripoli]
2014-10-05T18:23:01+03:00[Europe/Athens]

References

  1. SimpleDateFormat JavaDoc
  2. Java 8 – How to convert String to LocalDate
  3. Stackoverflow : simpledateformat parsing date with ‘Z’ literal
  4. Wikipedia : ISO 8601
  5. Time Zone and Offset Classes
  6. GMT VS UTC
  7. What is a Time Zone?
  8. Joda Time

How to convert String to Date – Java?

In this tutorial, we will show you how to convert a String to java.util.Date. Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways.

    // String -> Date
    SimpleDateFormat.parse(String);

    // Date -> String
    SimpleDateFormat.format(date);

Refer to table below for some of the common date and time patterns used in java.text.SimpleDateFormat, refer to this JavaDoc

LetterDescriptionExamples
yYear2013
MMonth in yearJuly, 07, 7
dDay in month1-31
EDay name in weekFriday, Sunday
aAm/pm markerAM, PM
HHour in day0-23
hHour in am/pm1-12
mMinute in hour0-60
sSecond in minute0-60

Note
You may interest at this Java 8 example – How to convert String to LocalDate

1. String = 7-Jun-2013

If 3 ‘M’, then the month is interpreted as text (Mon-Dec), else number (01-12).TestDateExample1.java

package com.mkyong.date;

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

public class TestDateExample1 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        String dateInString = "7-Jun-2013";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 00:00:00 MYT 2013
07-Jun-2013

2. String = 07/06/2013

TestDateExample2.java

package com.mkyong.date;

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

public class TestDateExample2 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String dateInString = "07/06/2013";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 00:00:00 MYT 2013
07/06/2013

3. String = Fri, June 7 2013

TestDateExample3.java

package com.mkyong.date;

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

public class TestDateExample3 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
        String dateInString = "Fri, June 7 2013";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 00:00:00 MYT 2013
Fri, Jun 07 2013

4. String = Friday, Jun 7, 2013 12:10:56 PM

TestDateExample4.java

package com.mkyong.date;

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

public class TestDateExample4 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
        String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";

        try {

            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Fri Jun 07 12:10:56 MYT 2013
Friday, Jun 07, 2013 12:10:56 PM

5. String = 2014-10-05T15:23:01Z

Z suffix means UTC, java.util.SimpleDateFormat doesn’t parse it correctly, you need to replace the suffix Z with ‘+0000’.TestDateExample5.java

package com.mkyong.date;

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

public class TestDateExample5 {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String dateInString = "2014-10-05T15:23:01Z";

        try {

            Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
            System.out.println(date);

            System.out.println("time zone : " + TimeZone.getDefault().getID());
            System.out.println(formatter.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Sun Oct 05 23:23:01 MYT 2014
time zone : Asia/Kuala_Lumpur
2014-10-05T23:23:01+0800

In Java 8, you can convert it into a java.time.Instant object, and display it with a specified time zone.TestDateExample6.java

package com.mkyong.date;

import java.time.*;

public class TestDateExample6 {

    public static void main(String[] argv) {

        String dateInString = "2014-10-05T15:23:01Z";

        Instant instant = Instant.parse(dateInString);

        System.out.println(instant);

        //get date time only
        LocalDateTime result = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneOffset.UTC.getId()));

        System.out.println(result);

        //get date time + timezone
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Africa/Tripoli"));
        System.out.println(zonedDateTime);

        //get date time + timezone
        ZonedDateTime zonedDateTime2 = instant.atZone(ZoneId.of("Europe/Athens"));
        System.out.println(zonedDateTime2);
        
    }

}

Output

2014-10-05T15:23:01Z
2014-10-05T15:23:01
2014-10-05T17:23:01+02:00[Africa/Tripoli]
2014-10-05T18:23:01+03:00[Europe/Athens]

References

  1. SimpleDateFormat JavaDoc
  2. Java 8 – How to convert String to LocalDate
  3. Stackoverflow : simpledateformat parsing date with ‘Z’ literal
  4. Wikipedia : ISO 8601
  5. Time Zone and Offset Classes
  6. GMT VS UTC
  7. What is a Time Zone?
  8. Joda Time

Java – How to get current date time?

In this tutorial, we will show you how to get the current date time from the classic Date and Calendar APIs, and also the new Java 8 date and time APIs – LocalDateTime and LocalDate

1. Code Snippets

For java.util.Date, just create a new Date()

 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43

For java.util.Calendar, uses Calendar.getInstance()

 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Calendar cal = Calendar.getInstance();
 System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43

For java.time.LocalDateTime, uses LocalDateTime.now()

 DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
 LocalDateTime now = LocalDateTime.now();
 System.out.println(dtf.format(now)); //2016/11/16 12:08:43

For java.time.LocalDate, uses LocalDate.now()

 DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
 LocalDate localDate = LocalDate.now();
 System.out.println(dtf.format(localDate)); //2016/11/16

2. Full Example

Review a full Java example to show you how to get the current date, time and display in a predefined format.GetCurrentDateTime.java

package com.mkyong;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

public class GetCurrentDateTime {

    private static final DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

    public static void main(String[] args) {

        Date date = new Date();
        System.out.println(sdf.format(date));

        Calendar cal = Calendar.getInstance();
        System.out.println(sdf.format(cal.getTime()));

        LocalDateTime now = LocalDateTime.now();
        System.out.println(dtf.format(now));

        LocalDate localDate = LocalDate.now();
        System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));

    }

}

Output

2016/11/16 12:08:43
2016/11/16 12:08:43
2016/11/16 12:08:43
2016/11/16

References

  1. Date JavaDoc
  2. Calendar JavaDoc
  3. SimpleDateFormat JavaDoc
  4. LocalDateTime JavaDoc
  5. LocalDate JavaDoc
  6. DateTimeFormatter JavaDoc

How to compare dates in Java?

Few examples show you how to compare two dates in Java. Updated with Java 8 examples.

1. Date.compareTo()

A classic method to compare two java.util.Date in Java.

  1. Return value is 0 if both dates are equal.
  2. Return value is greater than 0 , if Date is after the date argument.
  3. Return value is less than 0, if Date is before the date argument.

TestDate.java

package com.mkyong.date;

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

public class TestDate {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");

        System.out.println("date1 : " + sdf.format(date1));
        System.out.println("date2 : " + sdf.format(date2));

        if (date1.compareTo(date2) > 0) {
            System.out.println("Date1 is after Date2");
        } else if (date1.compareTo(date2) < 0) {
            System.out.println("Date1 is before Date2");
        } else if (date1.compareTo(date2) == 0) {
            System.out.println("Date1 is equal to Date2");
        } else {
            System.out.println("How to get here?");
        }

    }

}

Output

date1 : 2009-12-31
date2 : 2010-01-31
Date1 is before Date2

2. Date.before(), Date.after() and Date.equals()

A more user friendly method to compare two java.util.DateTestDate2.java

package com.mkyong.date;

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

public class TestDate2 {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");

        System.out.println("date1 : " + sdf.format(date1));
        System.out.println("date2 : " + sdf.format(date2));
        
        if (date1.after(date2)) {
            System.out.println("Date1 is after Date2");
        }

        if (date1.before(date2)) {
            System.out.println("Date1 is before Date2");
        }

        if (date1.equals(date2)) {
            System.out.println("Date1 is equal Date2");
        }

    }

}

Output

date1 : 2009-12-31
date2 : 2010-01-31
Date1 is before Date2

3. Calender.before(), Calender.after() and Calender.equals()

Example to compare two java.util.CalendarTestDate3.java

package com.mkyong.date;

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

public class TestDate3 {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");

        System.out.println("date1 : " + sdf.format(date1));
        System.out.println("date2 : " + sdf.format(date2));

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);

        if (cal1.after(cal2)) {
            System.out.println("Date1 is after Date2");
        }

        if (cal1.before(cal2)) {
            System.out.println("Date1 is before Date2");
        }

        if (cal1.equals(cal2)) {
            System.out.println("Date1 is equal Date2");
        }
    }

}

Output

date1 : 2009-12-31
date2 : 2010-01-31
Date1 is before Date2

4. Java 8

In Java 8, you can use the new isBefore(), isAfter(), isEqual() and compareTo() to compare LocalDate, LocalTime and LocalDateTime.

Review the following example to compare two java.time.LocalDateTestDate4.java

package com.mkyong.date;

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

public class TestDate4 {

    public static void main(String[] args) {

        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date1 = LocalDate.of(2009, 12, 31);
        LocalDate date2 = LocalDate.of(2010, 01, 31);

        System.out.println("date1 : " + sdf.format(date1));
        System.out.println("date2 : " + sdf.format(date2));

        System.out.println("Is...");
        if (date1.isAfter(date2)) {
            System.out.println("Date1 is after Date2");
        }

        if (date1.isBefore(date2)) {
            System.out.println("Date1 is before Date2");
        }

        if (date1.isEqual(date2)) {
            System.out.println("Date1 is equal Date2");
        }

        System.out.println("CompareTo...");
        if (date1.compareTo(date2) > 0) {

            System.out.println("Date1 is after Date2");

        } else if (date1.compareTo(date2) < 0) {

            System.out.println("Date1 is before Date2");

        } else if (date1.compareTo(date2) == 0) {

            System.out.println("Date1 is equal to Date2");

        } else {

            System.out.println("How to get here?");

        }
    }

}

Output

date1 : 2009-12-31
date2 : 2010-01-31
Is...
Date1 is before Date2
CompareTo...
Date1 is before Date2

References

  1. Date CompareTo JavaDoc
  2. Calendar before after JavaDoc
  3. LocalDate JavaDoc

Java 8 – How to Convert Instant to LocalDateTime?

Java 8 examples to show you how to convert from Instant to LocalDateTime

1. Instant -> LocalDateTime

The java.time.LocalDateTime has no concept of time zone, just provide a zero offset UTC+0.InstantExample1.java

package com.mkyong.date;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class InstantExample1 {

    public static void main(String[] argv) {

 // Parse a ISO 8601 Date directly
 //Instant instant = Instant.parse("2016-08-18T06:17:10.225Z");

        Instant instant = Instant.now();

        System.out.println("Instant : " + instant);

        //Convert instant to LocalDateTime, no timezone, add a zero offset / UTC+0
        LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

        System.out.println("LocalDateTime : " + ldt);

    }

}

Output

Instant : 2016-08-18T06:17:10.225Z
LocalDateTime : 2016-08-18T06:17:10.225

2. LocalDateTime -> Instant

InstantExample2.java

package com.mkyong.date;

import java.time.*;

public class InstantExample2 {

    public static void main(String[] argv) {

 // Hard code a date time
        LocalDateTime dateTime = LocalDateTime.of(2016, Month.AUGUST, 18, 6, 17, 10);

        System.out.println("LocalDateTime : " + dateTime);

        // Convert LocalDateTime to Instant, UTC+0
        Instant instant = dateTime.toInstant(ZoneOffset.UTC);

        System.out.println("Instant : " + instant);

    }

}

Output

Instant : 2016-08-18T06:17:10.225Z
LocalDateTime : 2016-08-18T06:17:10.225

References

  1. Wikipedia – ISO 8601 date format
  2. Instant JavaDoc
  3. LocaldateTime JavaDoc