Getting unix timestamp from Date()

JavaDate

Java Problem Overview


I can convert a unix timestamp to a Date() object by putting the long value into the Date() constructor. For eg: I could have it as new Date(1318762128031).

But after that, how can I get back the unix timestamp from the Date() object?

Java Solutions


Solution 1 - Java

getTime() retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.

Solution 2 - Java

To get a timestamp from Date(), you'll need to divide getTime() by 1000, i.e. :

Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691

or simply:

long unixTime = System.currentTimeMillis() / 1000L;

Solution 3 - Java

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class Timeconversion {
    private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH); //Specify your locale

    public long timeConversion(String time) {
        long unixTime = 0;
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:30")); //Specify your timezone
        try {
            unixTime = dateFormat.parse(time).getTime();
            unixTime = unixTime / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return unixTime;
    }
}

Solution 4 - Java

In java 8, it's convenient to use the new date lib and getEpochSecond method to get the timestamp (it's in second)

Instant.now().getEpochSecond();

Solution 5 - Java

I dont know if you want to achieve that in js or java, in js the simplest way to get the unix timestampt (this is time in seconds from 1/1/1970) it's as follows:

var myDate = new Date();
console.log(+myDate); // +myDateObject give you the unix from that date

Solution 6 - Java

Use SimpleDateFormat class. Take a look on its javadoc: it explains how to use format switches.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarvenView Question on Stackoverflow
Solution 1 - JavajackrabbitView Answer on Stackoverflow
Solution 2 - JavaPedro LobitoView Answer on Stackoverflow
Solution 3 - JavabhaskerView Answer on Stackoverflow
Solution 4 - JavawaterscarView Answer on Stackoverflow
Solution 5 - JavaelverdeView Answer on Stackoverflow
Solution 6 - JavaAlexRView Answer on Stackoverflow