javadatetimehex

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).


Solution

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