“YYYY-MM-dd和yyyy-MM-dd的区别”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
| 第26行: | 第26行: | ||
|2022-01-02 | |2022-01-02 | ||
|} | |} | ||
| + | <syntaxhighlight lang="java"> | ||
| + | import java.text.ParseException; | ||
| + | import java.text.SimpleDateFormat; | ||
| + | import java.util.Calendar; | ||
| + | import java.util.Date; | ||
| + | |||
| + | public class Test { | ||
| + | |||
| + | public static void main(String[] args) throws ParseException { | ||
| + | //定义格式化 | ||
| + | SimpleDateFormat fA = new SimpleDateFormat("yyyy-MM-dd"); | ||
| + | SimpleDateFormat fB = new SimpleDateFormat("YYYY-MM-dd"); | ||
| + | |||
| + | //生成日期 | ||
| + | Calendar c = Calendar.getInstance(); | ||
| + | //month – the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January. | ||
| + | c.set(2021, 11, 31); | ||
| + | Date d = c.getTime(); | ||
| + | |||
| + | |||
| + | //根据不同的格式化输出日期 | ||
| + | System.out.println(fA.format(d)); | ||
| + | System.out.println(fB.format(d)); | ||
| + | |||
| + | } | ||
| + | } | ||
| + | </syntaxhighlight><syntaxhighlight lang="console"> | ||
| + | 2021-12-31 | ||
| + | 2022-12-31 | ||
| + | </syntaxhighlight> | ||
2022年10月21日 (五) 07:52的版本
https://www.bilibili.com/video/BV1UG4y1p796
“yyyy-MM-dd”这种格式化对于年份的取值取的是当天所在的这个年份;
而“YYYY-MM-dd”取的年份是本周所在的这个年份。
所以要注意:跨年周的情况
比如:2021年12月27日到2022年1月2日是周一到周日
| 一 | 二 | 三 | 四 | 五 | 六 | 日 |
|---|---|---|---|---|---|---|
| 2021-12-27 | 2021-12-28 | 2021-12-29 | 2021-12-30 | 2021-12-31 | 2022-01-01 | 2022-01-02 |
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws ParseException {
//定义格式化
SimpleDateFormat fA = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fB = new SimpleDateFormat("YYYY-MM-dd");
//生成日期
Calendar c = Calendar.getInstance();
//month – the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
c.set(2021, 11, 31);
Date d = c.getTime();
//根据不同的格式化输出日期
System.out.println(fA.format(d));
System.out.println(fB.format(d));
}
}
2021-12-31
2022-12-31