17

How to get current time-stamp in UTC/GMT and then How to convert this time-stamp into seconds ? Itry this but its thrw exception

    SimpleDateFormat sdfu  = new SimpleDateFormat("yyyy-MM-dd kk:mm");
    Date udate = sdfu.parse(dateAndTimeUTC);
    long timeInMillisSinceEpoch123 = udate.getTime(); 
    long durationinSeconds2 = timeInMillisSinceEpoch123 / 1000;
    System.out.println("Time in Seconds UTC: " + durationinSeconds2);

Is there any better way to convert UTC/GMT time-stamp into seconds?

kreya
  • 1,091
  • 5
  • 24
  • 52

2 Answers2

49

get current seconds system long timestamp = System.currentTimeMillis() / 1000;

Dat Nguyen
  • 784
  • 1
  • 5
  • 14
  • 3
    @Limnic Your statement is false. The [Java documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()) states "**Returns:**
    the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC." The time difference since UTC is in UTC time and is not affected by time zones.
    – Agi Hammerthief Aug 23 '18 at 08:13
29

With Java 8+, you can use:

Instant.now().getEpochSecond()
yuen26
  • 871
  • 11
  • 12