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