gpt4 book ai didi

java - 如何将参数的日期转换为日期格式 yyyyMMdd

转载 作者:行者123 更新时间:2023-12-01 19:30:34 27 4
gpt4 key购买 nike

我想像这样将控制台保存到.txt中

Data_Bank_yyMMdd.txt

每次运行应用程序时。

以下是我根据当前时间保存控制台的方法:

SimpleDateFormat dtf = new SimpleDateFormat("yyMMdd");
Date date = new Date();

System.setOut(new PrintStream(new FileOutputStream("Data_Bank_" + dtf.format(date) + ".txt")));

但是,当我将运行配置参数与

2020-01-24

我也希望它自动格式化为 yyMMdd 。不像

this (the first one)

有人知道怎么做吗???无论如何,谢谢..

最佳答案

如果你可以使用Java 8或更高版本,那么建议使用 java.time 用于日期和时间的操作。

您可以使用 LocalDateDateTimeFormatter 解决您的问题:

public static void main(String[] args) {
// get the date of today
LocalDate today = LocalDate.now();
// and parse a given date with a
LocalDate someDate = LocalDate.parse("2020-01-24");

// define a formatter using your desired date pattern
DateTimeFormatter dtfShort = DateTimeFormatter.ofPattern("yyMMdd");

// print the dates using a built-in formatter
System.out.println("[ISO]\t" + today.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ "\t" + someDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
// print the dates using your custom formatter
System.out.println("[Short]\t" + today.format(dtfShort)
+ "\t\t" + someDate.format(dtfShort));
}

输出是这样的:

[ISO]   2020-01-22  2020-01-24
[Short] 200122 200124

应该易于用于文件输出,这应该使用 java.nio 来完成 如今。

关于java - 如何将参数的日期转换为日期格式 yyyyMMdd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59854631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com