Question

I am trying to get epoch time of today's date. But stuck with ParseException on Formatting date.

Snippet:-

SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
String str = df.format(Calendar.getInstance().getTime());
Date date = df.parse(str);
long epoch = date.getTime();
Log.i("Epoch" , String,valueOf(epoch));

How one can get today's epoch time?

Was it helpful?

Solution 2

To get Today's Epoch Time:-

 SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
 String _date = df.format(Calendar.getInstance().getTime());
 Long notificationID = strDateToUnixTimestamp(_date); //Gives Today Epoch Time.

 private static long strDateToUnixTimestamp(String dt) {
    DateFormat formatter;
    Date date = null;
    long unixtime;
    formatter = new SimpleDateFormat("dd/MM/yy");
    try {
        date = formatter.parse(dt);
    } catch (ParseException ex) {

        ex.printStackTrace();
    }
    unixtime = date.getTime() / 1000L;
    return unixtime;
}

To see the difference between current Time in Millis and Today's in Millis [Date 00:00:00].

Log.i("Notification ID", String.valueOf(notificationID) + ": "+ System.currentTimeMillis()/1000);

Posting SO and it's answer as I googled for few hours and found what i was looking for. Hope it may be helpful to others.

OTHER TIPS

If you're just interested in the current time since Jan 1 1970 UTC in milliseconds, use System.currentTimeMillis()see javadoc. No need to format and parse strings in the process.

To get an unix epoch timestamp from it, convert it to seconds by dividing with 1000.

Based on the comments and your own answer you seem to be interested in an epoch timestamp in some timezone. Use a Calendar for that, no need to format and parse strings here either:

Calendar c = Calendar.getInstance(); // today
c.setTimeZone(TimeZone.getTimeZone("UTC")); // comment out for local system current timezone
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.AM_PM, Calendar.AM);
long millistamp = c.getTimeInMillis();
long unixstamp = millistamp / 1000;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top