Android Milliseconds since time

I read all the docs and it seems not too much to really explain the date functions or the absence there.

I am trying to implement AlarmManger that needs time in milliseconds (ms) for a trigger. To check, I took the current time and added 5 seconds, and that was good.

// get a Calendar object with current time Calendar cal = Calendar.getInstance(); // add 5 minutes to the calendar object cal.add(Calendar.SECOND, 5); 

If I have a date and time, how will I get ms in that time.

Like "3/2/2011 08:15:00"

How do I turn this into milliseconds?

+4
source share
2 answers

Use this method.

Example:

method call for 3/2/2011 08:15:00

 D2MS( 3, 2, 2011, 8, 15, 0); 

Method

 public long D2MS(int month, int day, int year, int hour, int minute, int seconds) { Calendar c = Calendar.getInstance(); c.set(year, month, day, hour, minute, seconds); return c.getTimeInMillis(); } 
+13
source

When using AlarmManager, you have two choices when setting the alarm: the first is the time in seconds since the device was rebooted (do not understand this option) or, if you want an โ€œabsoluteโ€ time, then you need to provide UTC time in ms.

I think this should work - in the past I did something similar ...

 public long getUtcTimeInMillis(String datetime) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date date = sdf.parse(datetime); // getInstance() provides TZ info which can be used to adjust to UTC Calendar cal = Calendar.getInstance(); cal.setTime(date); // Get timezone offset then use it to adjust the return value int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis()); return cal.getTimeInMillis() + offset; } 

Personally, I would recommend using a non-localized format, for example yyyy-MM-dd HH:mm:ss for any used date / time if you want to serve users around the world.

International standard ISO 8601 yyyy-MM-dd HH:mm:ss.SSSZ , but I usually did not go that far.

+3
source

Source: https://habr.com/ru/post/1341915/


All Articles