Basic java date

prettyprintprettyprint
1 min read

Most used Java date conversions - format and parse.Accomplished using DateFormat Class and pattern

Format - Convert util.Date object to String

String pattern = "yyyy-mm-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = new Date();
System.out.println(simpleDateFormat.format(date));

Output

2023-21-22 19:21:42

Parse - Convert string to util.Date object

String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
try{
    Date date = simpleDateFormat.parse("03-15-2023");
    System.out.println(date);
}
catch(ParseException ex ){
    ex.printStackTrace();
}

Output

Wed Mar 15 00:00:00 GMT 2023

More...

If you want to create a date object strictly adhering to the pattern use setLenient(false). By default it's true.

Example:

String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
try{
      Date date = simpleDateFormat.parse("03-15-0");
      System.out.println(date);
      simpleDateFormat.setLenient(false);
      date = simpleDateFormat.parse("03-15-0");
      System.out.println(date);
}
catch(ParseException ex ){
    ex.printStackTrace();
}

Mon Mar 15 00:00:00 GMT 1

java.text.ParseException: Unparseable date: "03-15-0"at java.base/java.text.DateFormat.parse(DateFormat.java:395) at HelloWorld.main(HelloWorld.java:17)

Furthermore ...

Nowadays, use the newer implementation as follows,

   LocalDateTime date = LocalDateTime.now();
   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");
   String text = date.format(formatter);
   System.out.println(text);
   LocalDateTime parsedDate = LocalDateTime.parse(text, formatter);
   System.out.println( parsedDate.format(DateTimeFormatter.ISO_DATE_TIME));

2023-10-24 21:18:24 pm

2023-10-24T21:18:24

Official doc: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Try it in

https://www.programiz.com/java-programming/online-compiler/

0
Subscribe to my newsletter

Read articles from prettyprint directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

prettyprint
prettyprint

I am an application developer from bangalore who have been coding in java for around 6 years , python for around 1year and scala for around two years. Along the lines got into a little love triangle with javascript /extjs/css as well and after the break up I am missing them :) .