0

I have created below program in which I tried to compare date and time. but it is giving different answers in different compilers.

In tutorials point compiler it is working as expected : tutorialspoint

But, In repl.it compiler it is giving me wrong output : repl.it

Why this problem is happening?

let todayDate = () => {
    var today = new Date();
    var dateAndTime = today.toLocaleString('en-GB', { timeZone: 'Asia/Kolkata' })
    var fulldate = dateAndTime.split(",")[0].split("/")
    var dd = fulldate[0]
    var mm = fulldate[1]
    var yyyy = fulldate[2]

    return yyyy + '/' + mm + '/' + dd;
}

let currentTime = () => {
    var today = new Date();
    var dateAndTime = today.toLocaleString('en-GB', { timeZone: 'Asia/Kolkata' })
    var time = dateAndTime.split(",")[1].split(":")
    var hh = time[0].replace(/^\s+|\s+$/gm,'');
    var mm = time[1]
    var ss = time[2]

    return Date.parse(`${todayDate()} ${hh}:${mm}:${ss}`);
    
}

if (currentTime() > Date.parse(`${todayDate()} 18:00:00`) && currentTime() <  Date.parse(`${todayDate()} 22:52:58`)){
console.log('Welcome')
}
else{
  console.log('Comeback Later')
}

console.log(currentTime())
console.log(todayDate())
BB Mevada
  • 45
  • 7
  • This is the correct output: `Comeback Later` `1616434360000` `2021/03/22` – Manas Khandelwal Mar 22 '21 at 17:33
  • If you want portability, use ISO date format: `yyyy-mm-dd` – Barmar Mar 22 '21 at 17:33
  • @ManasKhandelwal but why it is showing different output in different compilers? You can change second time 22:52:58 to later and then check it. – BB Mevada Mar 22 '21 at 17:36
  • @BBMevada replit.com one seems to have some problem. I don't use these compilers that is why I don't know about it! – Manas Khandelwal Mar 22 '21 at 17:38
  • The output of *toLocaleString* is implementation dependent, so difference between implementations should be expected. `Date.parse(\`${todayDate()} ${hh}:${mm}:${ss}\`)` produces `NaN` at Replit, so results in an invalid date, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Mar 22 '21 at 23:10

0 Answers0