0

I am trying to get current android device time, and convert it into UTC timezone, then i need to convert it into Unix Timestamp.

I google it, found some solutions, tried few, but nothing helping me here.

This is what i am doing now.

  Date date;
  SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
  dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));

  SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

  date=  dateFormatLocal.parse( dateFormatGmt.format(new Date()) );

  date.getTime();

Output:

  • date(Its returning the correct UTC date time) Thu Jan 26 08:06:20 GMT+05:00 2017
  • date.getTime() returns 1485399980000

When i put this Timestamp in online tools, Its not returning right output.

Kindly guide me how to convert current UTC time into UnixTimestamp

Vao Tsun
  • 37,644
  • 8
  • 70
  • 98
dev90
  • 5,609
  • 11
  • 50
  • 122

1 Answers1

3

What you need is much simpler:

new Date().getTime()

It is alread in UTC. To get a Linux timestamp you have to divide this by 1000.

Henry
  • 40,427
  • 6
  • 56
  • 72
  • Thanks @Henry, `dateFormatGmt.format(new Date().getTime()/1000)` is giving me following output `1970-Jan-18 04:37:00` – dev90 Jan 26 '17 at 08:50
  • @Kirmani88 what you did in your last comment does not make sense. Java and Unix use the same epoch (1.1.1970, 0:00 UTC) but while Java counts milliseconds since then, Unix counts seconds (Btw. both ignore leap seconds). Therefore the factor 1000 to convert between both. You cannot mix Java and Unix conventions like you did. – Henry Jan 26 '17 at 18:52
  • Yes, I understood that after posting the comment. Thanks for the Help :) – dev90 Jan 30 '17 at 07:50