Java 以 YYYYMMDD 格式获取当前日期的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31138533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:41:48  来源:igfitidea点击:

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

java

提问by ron cohen

And how to print it as a string.

以及如何将其打印为字符串。

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

我试过了,但我得到了 (YYYMMMMDDD HHSSMM) 格式的日期:

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

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

以(YYYYMMDD)格式获取当前日期的最简单方法是什么?

采纳答案by HymanWhiteIII

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));
    }
}

回答by Hakim

Just use: SimpleDateFormat

只需使用:SimpleDateFormat

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

// Get the date today 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 reportDate = df.format(today);

// Print what date is today!
System.out.println("Report Date: " + reportDate);

http://www.mkyong.com/java/how-to-convert-string-to-date-java/

http://www.mkyong.com/java/how-to-convert-string-to-date-java/

回答by user902383

is that what you are looking for?

这就是你要找的吗?

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
System.out.println(LocalDate.now().format(formatter));