Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Epoch to Javascript Date and Date to Epoch?

Tags:

jquery

I am working one application that works with multiple time zone.

Here server return's Epoch date.

I need a function that can convert Epoch Date to JavaScript Date.

Also i have requirement to send JavaScript Date to Epoch Date to server back on post data.

like image 874
Parth Trivedi Avatar asked Dec 18 '22 21:12

Parth Trivedi


1 Answers

@Parth Trivedi i made two function for you.

$(document).ready(function () {
    alert("Date to Epoch:" + Epoch(new Date()));
    alert("Epoch to Date:" + EpochToDate(Epoch(new Date())));
});

//Epoch
function Epoch(date) {
    return Math.round(new Date(date).getTime() / 1000.0);
}

//Epoch To Date
function EpochToDate(epoch) {
    if (epoch < 10000000000)
        epoch *= 1000; // convert to milliseconds (Epoch is usually expressed in seconds, but Javascript uses Milliseconds)
    var epoch = epoch + (new Date().getTimezoneOffset() * -1); //for timeZone        
    return new Date(epoch);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
like image 116
Ankit Kathiriya Avatar answered Feb 09 '23 00:02

Ankit Kathiriya