How to get current time in milliseconds in android

I am trying to save a file with a name as the current date and time in milliseconds. and when reading a file I want to read the last one. Here is the code

Calendar rightNow = Calendar.getInstance(); long offset = rightNow.get(Calendar.ZONE_OFFSET) + rightNow.get(Calendar.DST_OFFSET); String sinceMidnight = Long.toString((rightNow.getTimeInMillis() + offset) % (24 * 60 * 60 * 1000)); return sinceMidnight+"_"+Filename; 
+51
android
May 13 '13 at 7:31
source share
4 answers

I think you can use this

 long time= System.currentTimeMillis(); 

this returns the current time in milliseconds. it will certainly work

 long time= System.currentTimeMillis(); android.util.Log.i("Time Class ", " Time value in millisecinds "+time); 

Here is my logcat using the function above

 05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157 

If you have doubts about milliseconds. Check here.

EDIT : the time zone I used to demonstrate the IST code, so if you milliseconds mentioned in the code that matches the time in the log from a different time zone, specify the IST zone.

EDIT . This is a simple approach. But if you need a time zone or any other details, I think this will not be enough. Also look at this approach using android api support

+184
May 13 '13 at 8:51
source share

The problem is that System. currentTimeMillis(); System. currentTimeMillis(); returns the number of milliseconds since 1970-01-01T00: 00: 00Z, but new Date() indicates the current local time. Adding ZONE_OFFSET and DST_OFFSET from the Calendar class gives UTC time.

 Calendar rightNow = Calendar.getInstance(); // offset to add since we're not UTC long offset = rightNow.get(Calendar.ZONE_OFFSET) + rightNow.get(Calendar.DST_OFFSET); long sinceMidnight = (rightNow.getTimeInMillis() + offset) % (24 * 60 * 60 * 1000); System.out.println(sinceMidnight + " milliseconds since midnight"); 
+19
May 13 '13 at 7:38
source share

try it

  Calendar c = Calendar.getInstance(); int mseconds = c.get(Calendar.MILLISECOND) 

an alternative would be

  Calendar rightNow = Calendar.getInstance(); long offset = rightNow.get(Calendar.ZONE_OFFSET) + rightNow.get(Calendar.DST_OFFSET); long sinceMid = (rightNow.getTimeInMils() + offset) % (24 * 60 * 60 * 1000); System.out.println(sinceMid + " milliseconds since midnight"); 
0
May 13 '13 at 7:38
source share
 Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int mSec = calendar.get(Calendar.MILLISECOND); 
-one
May 13 '13 at 7:39
source share



All Articles