0

I have a JavaScript issue which I can't seem to solve:

I convert a Date to timestamp, and when I convert it back, it shows the correct DateTime:

DateTime to Timestamp:

var ts = Math.floor(Date.now() / 1000);

and back - Timestamp to Date:

 var a = new Date(ts * 1000);
 var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
 var year = a.getFullYear();
 var month = months[a.getMonth()];
 var date = a.getDate();
 var hour = a.getHours();
 var min = a.getMinutes();
 var sec = a.getSeconds();
 var formattedTime = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;

The problem is when I do it with input data, instead of using the Date.now(), it converts to timestamp, but when I convert it back to dateTime, the Hour parameter is exactly 4 hours early.

var destinationDateTimeStr_ = document.getElementById("dateyear").value+"-"+document.getElementById("datemonth").value+"-"+document.getElementById("dateday").value+"T"+document.getElementById("datehour").value+":"+document.getElementById("dateminute").value+":00";

//convert date as string to timezone
var date2 = new Date(destinationDateTimeStr_); //2018-06-16T15:35:00
ts_ = Math.floor(date2 / 1000);

and back - Timestamp to Date:

 var a = new Date(ts_ * 1000);
 var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
 var year = a.getFullYear();
 var month = months[a.getMonth()];
 var date = a.getDate();
 var hour = a.getHours();
 var min = a.getMinutes();
 var sec = a.getSeconds();
 var formattedTime = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;


//returns: 2018-06-16T11:35:00 - 4 hours earlier

how can that be if all conversions are done on the same client (the same timezone)?

then I tried:

var offset = new Date().getTimezoneOffset(); 

but it returns -180 which is only 3 hours back and not 4

then I tried:

var tz = Intl.DateTimeFormat().resolvedOptions().timeZone; 

but it gives me a text (which means -2 hours in my case: Asia/Jerusalem)

What am I doing wrong?

marble
  • 51
  • 7
  • UTC and GMT timezone show that I'm +3 – marble Jun 16 '18 at 13:01
  • alert (Math.floor(new Date('2018-06-19T15:40:00') / 1000)); //produces wrong timestamp and alert( Math.floor(Date.now() / 1000)); //produces correct timestamp (you can test it by typing in the current datetime in the first line) – marble Jun 16 '18 at 13:32
  • Try: `let dat = new Date(Date.UTC(2018, 5, 16, 15, 57, 00)) console.log(Math.floor( dat/ 1000)); console.log( Math.floor(Date.now() / 1000));` Note that June is 5. Months start from 0 – Attersson Jun 16 '18 at 13:57
  • My code brought a -4 hours result, this code brings a +3 hours result. only Date.now() brings the correct result. I can't figure this out. – marble Jun 16 '18 at 14:49
  • 1
    Javascript Date has been known to cause problems. Forget this. Try https://momentjs.com/ – Attersson Jun 16 '18 at 14:57
  • it looks awesome! thanx, I am checking the code locally on my computer, But my client uses a shared hosting so I wont be able to install it. Thanx for all the effort, I will use it for my own needs. – marble Jun 16 '18 at 16:59
  • 1
    Actually using a CDN allows your client to use it. Check my answer. :) – Attersson Jun 16 '18 at 17:15

2 Answers2

1

(This answers follows the comments)

It has been made clear Javascript Date is known to cause problems and OP opted for momentjs.

If using a shared hosting prevents your client to install it directly, include it with a CDN such as https://cdnjs.com/libraries/moment.js/

Attersson
  • 4,755
  • 1
  • 15
  • 29
0

haha!! I should have looked for that... whoops. Thank you very much!

in the meanwhile, I wrote this (assuming that Date.now() returns the real accurate value always [which is probably not the case]):

function getTimestampMilisecondsGap()
{
        var currentdate = new Date(); 
        timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000); 
        //let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
    //timestamp_1 = Math.floor( dat/ 1000);
    timestamp_2 = Math.floor(Date.now() / 1000); //this one is suppose to produce a correct timestamp
    var addTimeStampMilisecs = 0;
    if (timestamp_2 > timestamp_1)
    {
        addTimeStampMilisecs = timestamp_2-timestamp_1;
    }
    else if (timestamp_2 < timestamp_1)
    {
        addTimeStampMilisecs = timestamp_1-timestamp_2;
    }
    return addTimeStampMilisecs;
}



//writing a timestamp to the database
var destinationDateTimeStr = document.getElementById("dateyear").value+"-"+document.getElementById("datemonth").value+"-"+document.getElementById("dateday").value+"T"+document.getElementById("datehour").value+":"+document.getElementById("dateminute").value+":00";

var date2 = new Date(destinationDateTimeStr);

var eventDateTS = Math.floor(date2 / 1000); //convert to timestamp (with incorrect timezone)
eventDateTS += getTimestampMilisecondsGap(); //add (or decrese) the number of miliseconds from the timestamp because this function that generates the tmestamp returns a wrong number (the hour in the converted date is wrong)

//write the correct eventDateTS to your DB here...
marble
  • 51
  • 7