4

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.

Parth Trivedi
  • 3,802
  • 1
  • 20
  • 40
  • 2
    What do you mean by epoch date? Why don't you show us some sample data? – Marc Dec 08 '15 at 06:49
  • 3
    I do know what a UNIX timestamp is.... btw did you hear of Google? "JS date to epoch" and the first hit has your answer... – Marc Dec 08 '15 at 06:55
  • Question already in stackoverflow. http://stackoverflow.com/questions/5722919/jquery-convert-number-to-date – Bhavik Jani Dec 08 '15 at 07:03

2 Answers2

12

@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>
Ankit Kathiriya
  • 1,221
  • 10
  • 17
  • I only fixed the intendation, but I have another suggestion to reduce the code size: `return new Date(epoch)`. But it's up to you to integrate that. – Marc Dec 08 '15 at 08:14
0
const epochToDateHuman = ({epochTime=0})=>{
const valueConvert = 60000 // Base convert to Minutes to milliseconds
const milliseconds = 1000 
const zone = (new Date().getTimezoneOffset() * -1 ) * valueConvert  //  Return subtract time zone 
const newEpoch = epochTime * milliseconds  // Convert new value in milliseconds

const dateConvert = new Date(newEpoch + zone) // New Date + Zone 
return dateConvert}



const epoch = 1619456956
epochToDateHuman({epoch})

This arrow function epochToDateHuman, receives as parameters named epochTime that you want to convert to a zone date, The const valueConvert is the basis for converting the zone obtained in minutes to Milliseconds, because Date (). getTimezoneOffset () returns your zone time difference in minutes and when we receive in epochTime we convert them to milliseconds multiplying by the constant milliseconds, like this we obtain newEpoch with a new value in milliseconds and zone in negative milliseconds that will be subtracted from newEpoch that passed to a new Date, we obtain the value for the zone of the date... Happy hacking

Zellathor!

ZellaThor
  • 1
  • 1
  • While this code block may answer the question, it would be best if you could provide a little explanation for why it does so. – nik7 Apr 26 '21 at 22:24