SimpleDateFormat类时间转换BUG
来源:互联网 发布:淘宝邮箱注册页面 编辑:程序博客网 时间:2024/05/29 16:10
今天在群里碰到一个有意思的问题
说 19910414000000字符串在经过SimpleDateFormat转换的时候会出现一小时精度误差。
当时我第一反应是不是时区出现问题。
排查发现不是。用严格模式来执行转换会抛出异常。
测试发现以下日期会出现精度异常时间位置全部为00
测试时间端1910+300年
1940 06-03 00:00:00 1940 06-03 01:00:00
1941 03-16 00:00:00 1941 03-16 01:00:00
1986 05-04 00:00:00 1986 05-04 01:00:00
1987 04-12 00:00:00 1987 04-12 01:00:00
1988 04-10 00:00:00 1988 04-10 01:00:00
1989 04-16 00:00:00 1989 04-16 01:00:00
1990 04-15 00:00:00 1990 04-15 01:00:00
1991 04-14 00:00:00 1991 04-14 01:00:00
不太清楚为什么,或许是算法问题吧,欢迎讨论
代码片段来自于Just Do Java群群主,
private static final Set<Integer> bigMonthSet = new HashSet<>(); private static final Set<Integer> smallMonthSet = new HashSet<>(); static { bigMonthSet.addAll(Arrays.asList(1, 3, 5, 7, 8, 10, 12)); smallMonthSet.addAll(Arrays.asList(4, 6, 9, 11)); } public static boolean isLeapYear(int year) { return year % 400 == 0 || (year % 100 != 0 && year % 4 == 0); } public static int getMaxDays(int year, int month) { if(bigMonthSet.contains(month)) { return 31; } if(smallMonthSet.contains(month)) { return 30; } if(isLeapYear(year)) { return 29; } return 28; } public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM-dd HH:mm:ss"); int startYear = 1910; for (int i = 0; i < 3000; i++) { int year = startYear + i; for (int j = 0; j < 12; j++) { int month = j + 1; int maxDays = getMaxDays(year, month); for (int k = 0; k < maxDays; k++) { int day = k + 1; String dateString = "" + year + " " + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day) + " 00:00:00"; if(!dateString . equals(sdf.format(sdf.parse(dateString)))) { System.out.println(dateString + "\t\t" + sdf.format(sdf.parse(dateString))); } } } } }
阅读全文
0 0
- SimpleDateFormat类时间转换BUG
- Java中的时间转换SimpleDateFormat
- SimpleDateFormat 时间转换错误问题
- SimpleDateFormat转换时间,12,24时间格式
- SimpleDateFormat转换时间,12,24时间格式
- SimpleDateFormat转换时间,12,24时间格式
- SimpleDateFormat转换时间,12,24时间格式
- SimpleDateFormat转换时间,12,24时间格式
- SimpleDateFormat转换时间,12,24时间格式
- SimpleDateFormat转换时间,12,24时间格式
- SimpleDateFormat转换时间12,24时间格式
- SimpleDateFormat转换时间,12,24时间格式
- 类 SimpleDateFormat时间格式
- Java日期转换SimpleDateFormat时间格式
- 时间获取与转换Calendar/SimpleDateFormat
- Java SimpleDateFormat 中英文时间格式化转换
- JAVA SimpleDateFormat 中英文时间格式化转换
- Calendar日历+Date时间+SimpleDateFormat转换格式
- 浅谈 MVP in Android
- css父元素透明度(opacity)对子元素的影响
- 08_c++访问控制和继承
- 工具类
- vivado(1)——创建工程
- SimpleDateFormat类时间转换BUG
- a'a
- 前端面试大全
- SpringMVC框架之HelloWorld
- Ubuntu 16.04出现:Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/
- 第一个spring boot示例
- HR教你如何判断一个公司的好坏?
- 文本文件编辑相关命令(二)删除,移动,复制
- js 中{},[]中括号,大括号使用详解