How To Convert Date Time In Hex In Android
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(); TimeZ
Solution 1:
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))
}
}
Solution 2:
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);
}
Solution 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
Post a Comment for "How To Convert Date Time In Hex In Android"