gpt4 book ai didi

java - 在Java中将“mm/yy”转换为“yyyy-mm-dd”

转载 作者:行者123 更新时间:2023-11-29 10:09:32 25 4
gpt4 key购买 nike

我需要将"11/17"字符串日期(2017年11月)转换为"2017-11-01"(2017年11月1日)。

用Java实现此目标的最佳方法是什么?

我试过了:

String dayMonthYear = "11/17";
dayMonthYear = "01/" + dayMonthYear;

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yy");
DateTime dt = formatter.parseDateTime(dayMonthYear);
dt.year().setCopy(dt.getYear() + 2000);

DateTimeFormatter dtfOut = DateTimeFormat.forPattern("yyyy-MM-dd");
dayMonthYear = dtfOut.print(dt);
System.out.println(dayMonthYear); // "2017-11-01";


和:

SimpleDateFormat dateFormatTwoDigitsYear = new SimpleDateFormat(TWO_DIGITS_YEAR_DATE_FORMAT);  //"dd/MM/yy"
SimpleDateFormat dateFormatFourDigitsYear = new SimpleDateFormat(FOUR_DIGITS_YEAR_DATE_FORMAT);// "yyyy-MM-dd"
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -100);//??? I AM NOT SURE WHY DO I NEEED THIS??
dateFormatTwoDigitsYear.set2DigitYearStart(calendar.getTime());
try
{
dayMonthYear = dateFormatFourDigitsYear.format(dateFormatTwoDigitsYear.parse(dayMonthYear));
}
catch (ParseException e)
{
log.error("Error while formatting date in yyyy-MM-dd format. Date is " + dayMonthYear);
}


我不确定为什么在第二个方法中需要此行:

calendar.add(Calendar.YEAR, -100);


他们两个都在工作。但是我不确定是否有更好的解决方案。

最佳答案

您无需为年份添加值。 2位数的值(17)会自动调整为2017。此外,无需在输入中添加第1天。如果一天不存在,SimpleDateFormat会自动设置为1:

// input format: MM/yy
SimpleDateFormat parser = new SimpleDateFormat("MM/yy");
// output format: yyyy-MM-dd
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(parser.parse("11/17"))); // 2017-11-01




PS:如果您需要将日期设置为另一天(而不是1天),则可以将日期设置为 Calendar并在格式化之前进行更改:

// parse the date
Date date = parser.parse("11/17");
// set to a Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// change to whatever day you want
cal.set(Calendar.DAY_OF_MONTH, whateverDayIwant);
// format it
System.out.println(formatter.format(cal.getTime()));




乔达时代

旧类( DateCalendarSimpleDateFormat)具有 lots of problemsdesign issues,并且它们已被新的API取代。

我已经看到您正在使用Joda-Time,因此这里是使用此API的方法。

在Joda-Time中,当您解析为 DateTime时,它将为所有缺少的字段(在这种情况下为日,小时,分钟等)设置默认值。但是此API还有许多其他类型,它们最适合每种用例。

由于输入只有月和年,因此您可以将其解析为 org.joda.time.YearMonth,然后将日期设置为1。这将创建一个 org.joda.time.LocalDate,可以直接打印(因为 toString()方法已经返回了日期)以您想要的格式):

DateTimeFormatter parser = DateTimeFormat.forPattern("MM/yy");
// parse to YearMonth
YearMonth ym = YearMonth.parse("11/17", parser);
// set day to 1
System.out.println(ym.toLocalDate(1)); // 2017-11-01


我更喜欢这种方法,因为您可以将其设置为所需的任何一天,并且不需要使用不需要/不在乎的字段(例如小时,分钟等)创建完整的 DateTime对象。

如果需要将此值存储在 String中,只需调用 toString()方法:

// store "2017-11-01" in a String
String output = ym.toLocalDate(1).toString();




格式 yyyy-MM-ddtoString()使用的默认格式。如果需要其他格式,可以将其传递给 toString()

// convert to another format (example: dd/MM/yyyy)
String output = ym.toLocalDate(1).toString("dd/MM/yyyy"); // 01/11/2017


或者您可以使用另一个 DateTimeFormatter

// convert to another format (example: dd/MM/yyyy)
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy");
String output = fmt.print(ym.toLocalDate(1)); // 01/11/2017




PS: dt.year().setCopy返回一个新对象,并且由于您没有将其分配给任何变量,因此该值会丢失-该方法不会更改原始的 DateTime对象,因此 dt不会被其行更改代码。



Java新日期/时间API

Joda-Time处于维护模式,并且已被新的API取代,因此,我不建议使用它来启动新项目。即使在 joda's website中,它也表示:“请注意,Joda-Time被认为是一个很大程度上“完成”的项目。没有计划进行重大增强。如果使用Java SE 8,请迁移到java.time(JSR-310)。” 。

如果您不能(或不想)从Joda-Time迁移到新的API,则可以忽略此部分。

如果您使用的是Java 8,请考虑使用 new java.time APIless bugged and less error-prone than the old APIs更容易。

如果您使用的是Java 6或7,则可以使用 ThreeTen Backport,这是Java 8的新日期/时间类的很好的反向端口。对于Android,您还需要 ThreeTenABP(有关如何使用 here的更多信息)。

下面的代码对两者都适用。
唯一的区别是包名称(在Java 8中为 java.time,在ThreeTen Backport(或Android的ThreeTenABP)中为 org.threeten.bp),但是类和方法的名称相同。

该代码与Joda-Time非常相似(API并不完全相同,但 they have lots of similarities)。您可以使用Java 8的 java.time.format.DateTimeFormatter并将输入解析为 java.time.YearMonth(或者,在Java 7的ThreeTen Backport中,使用 org.threeten.bp.format.DateTimeFormatter并解析为 org.threeten.bp.YearMonth):

DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM/yy");
YearMonth ym = YearMonth.parse("11/17", parser);
System.out.println(ym.atDay(1)); // 2017-11-01


如果需要将此值存储在 String中,只需调用 toString()方法:

// store "2017-11-01" in a String
String output = ym.atDay(1).toString();




格式 yyyy-MM-ddtoString()使用的默认格式。如果需要其他格式,则可以使用其他 DateTimeFormatter

// convert to another format (example: dd/MM/yyyy)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String output = fmt.format(ym.atDay(1)); // 01/11/2017

关于java - 在Java中将“mm/yy”转换为“yyyy-mm-dd”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936984/

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