Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to get the current date in YYYYMMDD format?

Tags:

java

And how to print it as a string.

I tried this but I get the date in (YYYMMMMDDD HHSSMM) format:

System.out.println(LocalDateTime.now());

What is the easiest way to get the current date in (YYYYMMDD) format?

like image 830
ron cohen Avatar asked Jun 30 '15 12:06

ron cohen


4 Answers

is that what you are looking for?

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
System.out.println(LocalDate.now().format(formatter));
like image 153
user902383 Avatar answered Oct 11 '22 18:10

user902383


This does the trick but may not be the easiest:

import java.util.*;
import java.text.*;

class Test {
    public static void main (String[] args) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();
        System.out.println(dateFormat.format(date));
    }
}
like image 22
JackWhiteIII Avatar answered Oct 11 '22 18:10

JackWhiteIII


DateTimeFormatter.BASIC_ISO_DATE.format(LocalDate.now());
like image 42
tmx Avatar answered Oct 11 '22 18:10

tmx


This is a very old question but gets me every time. There is a much simpler way now in one line:

String now = Instant.now().atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(now);

outputs: 2020-07-09

like image 37
markthegrea Avatar answered Oct 11 '22 19:10

markthegrea