riamob
riamob

Reputation: 299

hex string to datetime format

I am converting hex-string into a dateformat... I am getting wrong date time with the following.. not sure where I am making a mistake.

    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());

my output is 'Mon Jan 09 10:13:49 CST 2012'.. which is not correct (it should be 2011-12-8,22:13:30.0 -- format ignored for now).

Upvotes: 3

Views: 2419

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 339372

Avoid legacy date-time classes

You were using terribly-flawed date-time classes that are now legacy, supplanted by the modern java.time classes defined in JSR 310.

java.time

The java.time classes, in contrast to the legacy classes, use sane numbering. That means 1-12 month numbers, for January-December. So your code would work if using LocalDateTime rather than 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

Upvotes: 0

srkavin
srkavin

Reputation: 1180

Month in Java is represented by integer literals 0..11, that is January is 0, ..., and December is 11. In this code, Integer.parseInt(month, 16) returns 12, which the Calendar object shifts to January next year (by increasing year).

-EDIT-
Also, set HOUR_OF_DAY instead of HOUR in cal.set(Calendar.HOUR, Integer.parseInt(hour, 16));

Upvotes: 4

MByD
MByD

Reputation: 137382

Few notes:

  1. Month in the Calendar class is from 0-11, where 0 is January.
  2. The toString format may vary.
  3. You forgot the seconds:

    String second = s1.substring(12, 14);
    cal.set(Calendar.SECOND, Integer.parseInt(second, 16));
    

Upvotes: 2

Related Questions