java年月加1月,在java中解析字符串到日期格式默认为1和月到1月

I am trying to accept a user input of date in the format like : "2000 hrs, Thursday, July 20, 2015". I will then convert this to a date format to do operations on it. But the convertion from string to date is defaulting month to January and date to 1. Here is the code snippet :

String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, YYYY";

SimpleDateFormat userDateFormatter = new SimpleDateFormat(userDateFormat);

String reference_date = "2000 hrs, Thursday, July 20, 2015";

Date date = null;

try {

date = userDateFormatter.parse(reference_date);

} catch (ParseException e) {

System.out.println("Date must be in the format " + userDateFormat);

}

System.out.println(userDateFormatter.format(date));

The following method block prints :

2000 hrs, Thursday, January 01, 2015.

Any clue why?

解决方案

Because you used YYYY when you needed yyyy and July 20, 2015 was a Monday. You wanted something like

String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, yyyy";

SimpleDateFormat userDateFormatter = new SimpleDateFormat(

userDateFormat);

String reference_date = "2000 hrs, Monday, July 20, 2015";

which then outputs

2000 hrs, Monday, July 20, 2015

Then SimpleDateFormat Javadoc says (in part)

Letter Date or Time Component Presentation Examples

G Era designator Text AD

y Year Year 1996; 96

Y Week year Year 2009; 09

Java,处理字符串格式日期并获取特定月份的第一天和最后一天,通常需要用到`java.time`包下的`LocalDate`类。给定一个只包含份和月份字符串 "2024-09",可以按照以下步骤操作: 1. 首先,需要将字符串转换成`LocalDate`对象。假设当前默认日期格式是ISO 8601的 "yyyy-MM",可以使用`DateTimeFormatter`来解析这个格式: ```java String inputDate = "2024-09"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM"); LocalDate localDate = LocalDate.parse(inputDate, formatter); ``` 2. 接着,获取指定月份的第一天和最后一天。这里需要用到`MonthDay`类: ```java MonthDay firstOfMonth = MonthDay.of(localDate.getMonth(), 1); MonthDay lastOfMonth = MonthDay.of(localDate.getMonth().getValue() + 1, 1).minusDays(1); // 注意一是因为月份是从0开始计数的 ``` `MonthDay.of(monthValue, 1)`返回该第一天,而`MonthDay.of(monthValue+1, 1).minusDays(1)`返回下个的第一天,因为我们需要上个的最后一天。 3. 将`MonthDay`转换回`LocalDate`,并格式化输出: ```java ZonedDateTime firstDay = ZonedDateTime.of(localDate.atStartOfDay(), ZoneId.systemDefault()); LocalDate startDate = firstDay.toLocalDate(); ZonedDateTime lastDay = ZonedDateTime.of(lastOfMonth.atEndOf(MonthDay::range), ZoneId.systemDefault()); LocalDate endDate = lastDay.toLocalDate(); // 格式日期输出 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String startDateStr = startDate.format(dateFormatter); String endDateStr = endDate.format(dateFormatter); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值