java ddmmyy,java – 将字符串解析为本地日期不使用所...

由于这个问题实际上是关于新的java.time-package而不是SimpleDateFormat,我将引用relevant section:

Year: The count of letters determines the minimum field width below

which padding is used. If the count of letters is two, then a reduced

two digit form is used. For printing, this outputs the rightmost two

digits. For parsing, this will parse using the base value of 2000,

resulting in a year within the range 2000 to 2099 inclusive.

我们看到Java-8使用默认值2000-2099的范围,而不是像SimpleDateFormat那样,相对于今天的范围为-80年,直到20年.

如果你想配置它,那么你必须使用appendValueReduced().这是一个不方便的设计,但可能,请看这里:

String s = "150790";

// old code with base range 2000-2099

DateTimeFormatter dtf1 =

new DateTimeFormatterBuilder().appendPattern("ddMMyy").toFormatter();

System.out.println(dtf1.parse(s)); // 2090-07-15

// improved code with base range 1935-2034

DateTimeFormatter dtf2 =

new DateTimeFormatterBuilder().appendPattern("ddMM")

.appendValueReduced(

ChronoField.YEAR, 2, 2, Year.now().getValue() - 80

).toFormatter();

System.out.println(dtf2.parse(s)); // 1990-07-15

顺便说一句,如果你真的想要基于周的年份,那么你必须使用Y而不是y或相应的字段IsoFields.WEEK_BASED_YEAR.关于您没有任何其他与周相关的字段的事实,我会假设正常的日历年,而不是基于周的日历年.

好的,以下是满足您需求的C语言程序。 ``` #include <stdio.h> #include <time.h> int main() { char time[11]; // 存储UTC时间 char d[7]; // 存储UTC日期 // 获取用户输入 printf("请输入UTC时间(格式为HHMMMSS.SSS):"); scanf("%s", time); printf("请输入UTC日期(格式为DDMMYY):"); scanf("%s", d); // 将UTC时间和日期转换为struct tm结构体 struct tm utc_tm; utc_tm.tm_hour = (time[0] - '0') * 10 + (time[1] - '0'); utc_tm.tm_min = (time[2] - '0') * 10 + (time[3] - '0'); utc_tm.tm_sec = (time[4] - '0') * 10 + (time[5] - '0'); utc_tm.tm_year = (d[4] - '0') * 10 + (d[5] - '0') + 100; // 加上1900年 utc_tm.tm_mon = (d[2] - '0') * 10 + (d[3] - '0') - 1; // 月份从0开始 utc_tm.tm_mday = (d[0] - '0') * 10 + (d[1] - '0'); // 计算UTC时间距离1970年1月1日0时0分0秒的秒数 time_t utc_time = mktime(&utc_tm); // 将UTC时间转换为北京时间 struct tm *beijing_tm = localtime(&utc_time); beijing_tm->tm_hour += 8; // 北京时间比UTC时间快8小时 mktime(beijing_tm); // 更新struct tm结构体中的其他字段 // 输出北京时间和日期 printf("北京时间:%04d-%02d-%02d %02d:%02d:%02d\n", beijing_tm->tm_year + 1900, beijing_tm->tm_mon + 1, beijing_tm->tm_mday, beijing_tm->tm_hour, beijing_tm->tm_min, beijing_tm->tm_sec); return 0; } ``` 程序的主要逻辑是,先将用户输入的UTC时间和日期转换为struct tm结构体,然后使用mktime函数将其转换为距离1970年1月1日0时0分0秒的秒数,再使用localtime函数将该秒数转换为北京时间的struct tm结构体,最后输出北京时间和日期。需要注意的是,北京时间比UTC时间快8小时,因此需要将struct tm结构体中的小时字段加上8。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值