How to format datetime stamp with Javascript and PHP - javascript

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.

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

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.

Related

Convert a string of (for example) Y-m-d from PHP to the equivalent date format in JS

I have a PHP variable which is a date format string, it is "Y-m-d" but could be other date format strings, I'd like to pass this to a script which requires a JS date format string.
Therefore my Y-m-d from PHP is the equivalent of YYYY-MM-DD in JS.
What can I do on either the PHP or JS side to convert the PHP based date format string of Y-m-d to the JS equivalent?
I am looking to convert the date format string itself, not the actual date.
I'm really not sure on what your issue is. But I've spun up a local version of what you're using and I've created the following code:
<input value="<?php echo date('Y-m-d'); ?>" id="litepicker">
<script src="https://cdn.jsdelivr.net/npm/litepicker/dist/js/main.js"></script>
<script>
var picker = new Litepicker({
element: document.getElementById('litepicker'),
format: 'D MMM, YYYY',
});
</script>
As you can see, its a new Litepicker instance, formatted to look nicely, but the input element has the value set to what you'd get back from the database, and it looks like this on screen:
If I'm misunderstanding you, please let me know. But I cannot see the issue.

Having trouble formatting a date in javascript from MySQL

I'm not very experienced in ajax and having trouble formatting my date from a MySQL database.
I've tried using the php date() function but can't seem to get it to work properly. What would be the best way to format the date in this?
$(document).ready(function(){
$.ajax({
type: "GET",
url: "../api/presentation/read.php",
dataType: 'json',
success: function(data) {
var response="";
for(var user in data){
response += "<tr>"+
"<td>"+data[user].date+"</td>"+
"<td>"+data[user].title+"</td>"+
"<td>"+data[user].speaker+"</td>"+
"<td><a href='update.php?id="+data[user].id+"'>Edit</a> | <a href='#' onClick=Remove('"+data[user].id+"')>Remove</a> | <a href='#' onClick=Active('"+data[user].id+"')>Active</a></td>"+
"</tr>";
}
$(response).appendTo($("#presentations"));
}
});
});
I have tried something along the lines of
"<td><?php echo date("+data[user].date+",dd-mm); ?></td>"+
This gives an output of "+01am31am[00000000UTCThu, 01 Jan 1970 00:00:00 +0000].01am31UTC+" which I suspect is because no value is being given to the date function?
I'd like the output to be in the format of dd-mm HH-MM instead of the MySQL datetime format of "2019-10-29 10:00:00"
You are mixing PHP and JavaScript in a wrong way.
First, you MUST know that PHP is executed on server side, BEFORE any HTML or JavaScript exists on your browser.
That said, lets read your attempt again:
""
Here, the PHP part of script will be run on server side, and the data[...] Variable don't exists there, also it's inside a string (between double quotes). Since this string is not a valid date, it will output the start of unix epoch.
To solve this, you need to separate your concerns here.
First way
Your php script called by ajax should return the date in some valid date format. I suggest using ISO8601 format since JavaScript parses this format automatically when using Date object.
Use JavaScript to format that date in the desired output format.
Second way:
Directly convert the date on PHP using the date function, but: you do it entirely on the PHP script. Don't mix both languages. They are totally separated and runs in different moment's and have isolated scopes.
Make the change in your Select query and then do as you have now.
SELECT DATE_FORMAT(NOW(), '%d.%m.%Y %H:%i:%s')
Result
DATE_FORMAT(NOW(), '%d.%m.%Y %H:%i:%s')
27.10.2019 20:40:41
instead of the function now() put in your columnname

Converting a mysql UTC_TIMESTAMP to CST and MST using Javascript

I've done endless searching but cannot find a solution that works for me. I am storing records in a mysql database that logs the UTC time it was created (UTC_TIMESTAMP()). I need to present the data to the user (using JavaScript) in their local time. I've tried the following and it is not working:
JavaScript:
function localizeDateStr(dateToConvert,divId){
newDate = new Date(dateToConvert);
document.getElementById(divId).innerHTML = newDate.toString();
}
HTML:
<div id="<?php echo $divId ?>" class="td-short"></div>
<script type="text/javascript">window.onload = localizeDateStr('<?php echo $entryTime;?>','<?php echo $divId;?>');</script>
The UTC date that is stored in the db is the same date that is being displayed.I am not seeing a converted date. Any help would be appreciated. Please advise.
Parsing a string through the Date constructor (or through Date.parse) is very sensitive to the format of the input string. With the value you gave in comments '2019-03-20 17:43:53', most implementations will interpret this in terms of local time. However, the specification does not require conformance of that, as it only describes a very particular format. Anything else is implementation dependent.
Assuming your strings are consistently in this format, and you want it interpreted as UTC, your options are:
Adjust the string to include a T separator between date and time parts, and end with Z to indicate UTC.
var newDate = new Date(dateToConvert.replace(' ','T') + 'Z');
Parse the string yourself:
var parts = dateToConvert.split(/[-: ]/g).map((x) => parseInt(x));
parts[1]--; // Months are 0-11, so adjust
var newDate = new Date(Date.UTC(...parts));
Use a library like Luxon:
var dt = luxon.DateTime.fromFormat(dateToConvert,
'yyyy-MM-dd HH:mm:ss', { zone: 'UTC' });
var newDate = dt.toJSDate();
or Moment:
var newDate = moment.utc(dateToConvert).toDate();

Correctly format times between client (javascript) and the server (PHP)

I have a date object in javascript that goes as follows:
var date = 2014-12-01T00:00:00.000Z
And if I do:
var date = new Date(date);
date.setUTCMonth(date.getUTCMonth()+1);
Then the toISOString() method shows the expected value:
2015-01-01T00:00:00.000Z
But when I send that date time string through a POST to a PHP script and parse it back to a date using the DateTime class, I get this:
2014-12-31 19:00:00 -0500
I have tried setting the timezone using the DateTimeZone class and setting the timezone to my own and UTC without luck:
new DateTime($_POST['DateTime'],new DateTimeZone('America/Mexico_City'));
new DateTime($_POST['DateTime'],new DateTimeZone('UTC'));
Is there a way to set the timezone in javascript, using the Date class? Is there another way to work around this? I have small if not zero experience at all dealing with timezones.
Update:
Here's my ISO-formatted time string as per the toISOString() method (javascript):
2014-09-01T00:00:00.000Z
And here are the contents of my $_POST var as per print_r():
Array (
[DateTime] => 2014-09-01T00:00:00.000Z
)
Here's the output of my formatter function, using the '%c' format (es_MX locale):
dom 31 ago 2014 19:00:00 CDT
And the mentioned formatter function:
function formatDate($date) {
return utf8_encode(strftime('%c', $date->getTimestamp()));
}
I think when you send the date-string, it's somehow in different format. At least when I tested this, it works as expected:
$a = new DateTime('2015-01-01T00:00:00.000Z');
echo $a->format('Y-m-d H:i:s'); // Outputs '2015-01-01 00:00:00'
Demo here.
The issue you are getting is that when you use the following format
$date = '2015-01-01T00:00:00.000Z';
You are specifying a timezone.
Notice the "Z" at the end of your date, using it is the equivalent of "nautical timezone (GMT)"
Therefore when you try to run this code, you will get the exact same date which is not what you expect even when you have specified the DateTimeZone as a constructor parameter.
$dateTime = new DateTime($date, new DateTimeZone('America/Mexico_City'));
echo $dateTime->format('c'). "\n"; // 2015-01-01T00:00:00+00:00
$dateTime = new DateTime($date, new DateTimeZone('UTC'));
echo $dateTime->format('c'). "\n"; //2015-01-01T00:00:00+00:00
This is expected PHP behavior and is documented in the DateTime::__construct documentation under the $timezone parameter:
Note:
The $timezone parameter and the current timezone are ignored when the
$time parameter either is a UNIX timestamp (e.g. #946684800) or
specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
In your case you are specifying a timezone directly with in your date (the "Z") and this is why the DateTimeZone object is ignored.
To avoid this and set a custom time zone either set it in the date time string or get rid of the Z.:
$date = '2015-01-01T00:00:00.000';
$dateTime = new DateTime($date, new DateTimeZone('America/Mexico_City'));
echo $dateTime->format('c'). "\n"; // 2015-01-01T00:00:00-06:00
$dateTime = new DateTime($date, new DateTimeZone('UTC'));
echo $dateTime->format('c'). "\n"; // 2015-01-01T00:00:00+00:00
$date = '2015-01-01T00:00:00.000 America/Mexico_City';
$dateTime = new DateTime($date);
echo $dateTime->format('c'). "\n"; //2015-01-01T00:00:00-06:00
See the code working for different versions of PHP here: Demo
Also take a look at this related question I asked recently: PHP DateTime Timezones - Constructor vs Setter method

Trying to parse date using new Date(). but keep getting wrong results

I am trying to parse a date string i get from php through ajax call(which is irrelevant for now) using new Date().
however i keep getting wrong results.
My string is 2013-05-09 20:56:17
When i do
var something = new Date("2013-05-09 20:56:17");
alert(something.getMonth());
It keeps alerting 0
In my opinion for some reason new date cant parse this string.
Is there a way to specify the date format for new Date() in JS ?
My current solution is to import php's: date() and strtotime() and use them :
alert(date('m', strtotime("2013-05-09 20:56:17")));
This works however I have to use external js lib and I am pretty sure there is a better JS way to achieve that.
If you use slashes instead of hyphens, it works:
var something = new Date("2013/05/09 20:56:17");
alert(something.getMonth());
It's easy enough to replace any hyphens in a string with slashes first if you need to (say, if you were getting the date string from somewhere else):
var something = new Date("2013-05-09 20:56:17");
something = something.replace('-', '/');
It seems JavaScript's Date constructor doesn't recognize date formats with hyphens, or at least not that particular format.
Choose a different format specifier in PHP for your ajax dates. The format you expect and the format expected by the javascript are different.
var something = new Date("2013-05-09T20:56:17");
Note the 'T' which appears as a literal separator and marks the beginning of time per ISO 8601
Reference for various [browser] javascript date formats
W3 DateTime
Microsoft IE DateTime
Mozilla [Firefox] DateTime
Google DateJs
And lastly, the PHP date format specifier list:
PHP Date
PHP DateTime
Note the 'DATE_ISO8601'; but I suggest not using that at this time. Instead use 'DATE_ATOM' which may produce a date format more widely supported (comments suggest it makes iPhones happier and no issues with other browsers).
To use it in PHP:
$something = new DateTime('NOW');
echo $something->format('c');
echo $something->format(DateTime::ATOM);

Categories

Resources