java 取得现存时间,到目前为止的字符串有时完整日期存在有时我只能在Java中获得年份...

So am parsing json and sometimes the string I receive which contains the date comes full(dd-mm-yyyy) , and sometimes I only receive yyyy which I dont seem to able to convert to date ,so if anyone can help

解决方案

As per your business requirement, you can default the month and the day-of-month to the required value using DateTimeFormatterBuilder#parseDefaulting e.g. in the following code, I have defaulted the month and the day-of-month to that of today:

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

import java.time.format.DateTimeFormatterBuilder;

import java.time.temporal.ChronoField;

import java.util.Locale;

class Main {

public static void main(String[] args) {

// Test

System.out.println(parseToDate("10-10-2020"));

System.out.println(parseToDate("2020"));

}

static LocalDate parseToDate(String str) {

LocalDate today = LocalDate.now();

DateTimeFormatter formatter = new DateTimeFormatterBuilder()

.appendPattern("[dd-MM-uuuu][uuuu]")

.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue())

.parseDefaulting(ChronoField.DAY_OF_MONTH, today.getDayOfMonth())

.toFormatter(Locale.ENGLISH);

return LocalDate.parse(str, formatter);

}

}

Output:

2020-10-10

2020-12-12

Note: The pattern, [dd-MM-uuuu][uuuu] has two optional patterns, dd-MM-uuuu and uuuu.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值