chris
chris

Reputation: 36937

Create a timestamp that would be equal to yyyy-mm-dd 00:00:00 or 23:59:59

What I have is a user selected/provided date string yyyy-mm-dd. Based on the input the user uses. I want to create a time stamp that is equal to either start of day midnight 00:00:00 or end of day midnight 23:59:59

I would like to do this in pure javascript. But the UTC/GMT automatically offsetting things is throwing it through a loop. Client side I am seeing Midnight, server side I am seeing midnight + offset, example from California. The timestamp equals yyyy-mm-dd 08:00:00

Is there a means of always coming up with 00:00:00 or 23:59:59?

My current and slightly working attempt is

function yyyy_mm_ddToTS(str, beforeMidnight)
{
    //if beforeMidnight == true, 23:59:59 is appended to the yyyy-mm-dd string
    if(typeof str !== 'undefined')
    {
        //validate str format = yyyy-mm-dd
        var re = /^\d{4}-\d{1,2}-\d{1,2}$/;
        if(re.test(str) == false){msgDisplayBox(null, 'Invalid date string use: yyyy-mm-dd', null);return false;}
    }
    append_hh_mm_ss = ' 00:00:00';
    if(typeof beforeMidnight !== 'undefined')
    {
        if(whatDataType(beforeMidnight) == "boolean")
        {
            if(beforeMidnight == true)
            {
                append_hh_mm_ss = ' 23:59:59';
            }
        }
    }
    var newStr = str+append_hh_mm_ss;
    var d = newStr.match(/\d+/g);
        //d = d.join(',');
        console.log(d[0], d[1] - 1, d[2], d[3], d[4], d[5]);
    var dateString = new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]);
        dateString.setHours(0,0,0,0);
    return dateString.getTime();
}

Which returns yyyy-mm-dd 08:00:00 not yyyy-mm-dd 00:00:00 when converted server side later

Upvotes: 0

Views: 218

Answers (1)

mdolbin
mdolbin

Reputation: 936

Try to use UTC date timestamp instead of Date.getTime()

var cDate = new Date();
var UTCDateMorning = Date.UTC(cDate.getFullYear(),cDate.getMonth(),cDate.getDate(),0,0,0);
var UTCDateMidnight = Date.UTC(cDate.getFullYear(),cDate.getMonth(),cDate.getDate(),23,59,59);

Upvotes: 1

Related Questions