1

The main issue: I gather the initial parameter in the datetime format, and use php date function to convert it to a readable format. From this format, I need to convert the date back to the same datetime parameter using javascript.

I have tried the getTime() function in javascript to get a datetime parameter conversion.

<?php
    $_REQUEST['date'] = 1500786000;
    $date=date('Y-m-d', $_REQUEST['date']);
    echo "<span id='date'>$date</span>";
?>
<script>
    var pdate=new Date('#date').val().replace(/-/,'\/'));
    console.log(pdate.getTime());
</script>

The original datetime parameter starts as 1500786000, is formatted as 2017-02-23 via PHP. The javascript conversion is 1500786000000, three 0s off from the expected format.

I would prefer not to use an alternative library, so anything that can be used in native javascript would be most helpful.

PrakashG
  • 1,642
  • 5
  • 20
  • 30
alrightgame
  • 341
  • 2
  • 7
  • 20
  • 4
    The PHP value there is a Unix timestamp, measuring the number of seconds since midnight on 1st January 1970. The JS version is similar but measures in milliseconds - so it's 1000 times bigger (the 3 extra 0s you noticed). Why is it hard to multply/divide by 1000 as needed? – Robin Zigmond Feb 13 '19 at 17:00
  • Possible duplicate of [Convert PHP date into javascript date format](https://stackoverflow.com/questions/10837022/convert-php-date-into-javascript-date-format) – aynber Feb 13 '19 at 17:00
  • @RobinZigmond : Instead of a comment ,can you please create an answer so that the person who asked this question can accept it as the correct answer .. It seems yours is indeed the correct answer. thanks – Gagan Feb 13 '19 at 17:15

2 Answers2

3

If you follow the same steps this is as expected. You just need to divide the value by 1000 to get the value you are expecting.

The original datetime parameter starts as 1500786000 because it's in seconds.

In JavaScript it will return the number of milliseconds since 1970/01/01.

var seconds = new Date().getTime() / 1000; // if you want it to be seconds
prime
  • 14,464
  • 14
  • 99
  • 131
  • @cr05s19xx suggests "You could also use the static method now, i.e. var seconds = Date.now() / 1000;" – Gary Feb 13 '19 at 19:43
0

Why don't you set both values in that span and use that as below:

<?php
    $_REQUEST['date']=1500786000;
    $date=date('Y-m-d', $_REQUEST['date']);
    echo "<span id='date' data-date='".$_REQUEST['date']."'>$date</span>";
?>
<script>
    var visibleDate= $('#date').val(); //You actual visible date
    var rawDate= $('#date').data('date'); //You raw date
</script>

You don't need to make conversion in JS again. Hope it helps you.

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18