我正在将十六进制字符串转换为日期格式...我收到以下错误的日期时间..不确定我在哪里犯了错误。
String s1="07:db:0c:08:16:0d:1e:00"; //2011-12-8,22:13:30.0
s1 = s1.replaceAll(":", "");
String year = s1.substring(0, 4);
String month = s1.substring(4, 6);
String day = s1.substring(6, 8);
String hour = s1.substring(8, 10);
String minute = s1.substring(10, 12);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Integer.parseInt(year, 16));
cal.set(Calendar.MONTH, Integer.parseInt(month, 16));
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day, 16));
cal.set(Calendar.HOUR, Integer.parseInt(hour, 16));
cal.set(Calendar.MINUTE, Integer.parseInt(minute, 16));
System.out.println(cal.getTime());
我的输出是“Mon Jan 09 10:13:49 CST 2012”..这是不正确的(应该是 2011-12-8,22:13:30.0 - 现在忽略格式)。
Integer.parseInt(month, 16)
返回 12,Calendar 对象将移至明年一月(通过增加年份)。-编辑-
另外,在 HOUR_OF_DAY
HOUR
而不是 cal.set(Calendar.HOUR, Integer.parseInt(hour, 16));
String second = s1.substring(12, 14);
cal.set(Calendar.SECOND, Integer.parseInt(second, 16));
java.time 类所取代。
类使用合理的编号。这意味着 1 月至 12 月的 1-12 个月数字。因此,如果使用 LocalDateTime
而不是
Calendar
,您的代码将有效。String input = "07:db:0c:08:16:0d:1e:00"; //2011-12-8,22:13:30.0
input = input.replaceAll( ":" , "" );
String year = input.substring( 0 , 4 );
String month = input.substring( 4 , 6 );
String day = input.substring( 6 , 8 );
String hour = input.substring( 8 , 10 );
String minute = input.substring( 10 , 12 );
LocalDateTime ldt =
LocalDateTime.of(
Integer.parseInt( year , 16 ) ,
Integer.parseInt( month , 16 ) ,
Integer.parseInt( day , 16 ) ,
Integer.parseInt( hour , 16 ) ,
Integer.parseInt( minute , 16 )
);
System.out.println( "ldt = " + ldt );
ldt.toString() = 2011-12-08T22:13