How to convert date time in hex in android

只谈情不闲聊 提交于 2019-12-25 10:50:31

问题


I need to convert date and time in hex code for writing it on IOT device. Here is my code

private String getDateTimeToHexa() { 

Calendar mCalendar = Calendar.getInstance();
TimeZone gmtTime =  TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName());

    mCalendar.setTimeZone(gmtTime);
    final Date date = mCalendar.getTime();
    return Long.toHexString(date.getTime());
}

It is returning 11 digits hex code I need 8 digits, just like date and time in hex is 47C7EDE0 for this date 12:34:56 29/Feb/2008

Please help


回答1:


Try this:

 private String getDateTimeToHexa() {
        Calendar mCalendar = Calendar.getInstance();
        TimeZone gmtTime =  TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName());
        mCalendar.setTimeZone(gmtTime);
        final Date date = mCalendar.getTime();
        return Long.toHexString(date.getTime()/1000);
    }



回答2:


import java.util.Calendar;
import java.util.Date;
public class Date {
    public static void main(final String[] args)
    {
    final Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DATE, 15);
    cal.set(Calendar.MONTH, Calendar.DECEMBER);
    cal.set(Calendar.YEAR, 2005);
    cal.set(Calendar.HOUR, 17);
    cal.set(Calendar.MINUTE, 35);
    cal.set(Calendar.SECOND, 20);
    final Date date = cal.getTime();

    System.out.printf("Date %s is encoded as: %s\n", date, Long.toHexString(date.getTime()));
    // decode with: new Date(Long.parseLong("1082f469308", 16))
}

}




回答3:


Instead of returning

return Long.toHexString(date.getTime());

Return following

return Long.toHexString(date.getTime()/1000);

As correctly pointed out by @shmosel that date.getTime() return time in a millisecond and if you want 8 digit Hex format then it needs to be converted in the second format.

The return type of Date can be found here



来源:https://stackoverflow.com/questions/45136264/how-to-convert-date-time-in-hex-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!