# Basic java date

---

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

**Format** - Convert util.Date object to String

```java
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

```java
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:

```java
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](http://DateFormat.java:395)) at HelloWorld.main([HelloWorld.java:17](http://HelloWorld.java:17))

### Furthermore ...

Nowadays, use the newer implementation as follows,

```java
   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](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)

Try it in

[https://www.programiz.com/java-programming/online-compiler/](https://www.programiz.com/java-programming/online-compiler/)
