Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hex string to datetime format

Tags:

java

datetime

hex

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

like image 785
riamob Avatar asked Dec 31 '25 04:12

riamob


2 Answers

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

like image 150
srkavin Avatar answered Jan 02 '26 18:01

srkavin


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));
    
like image 27
MByD Avatar answered Jan 02 '26 17:01

MByD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!