Converting a mysql UTC_TIMESTAMP to CST and MST using Javascript - 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();

Related

Format JSON DateTime

I currently have all my dates being returned with the letter T in my JSON Strings. EX: 2019-02-03T06:48:07. Is there a way to change the JSON String to return as 02-03-2019 06:48:07?
I am also using javascript to load the dates currently into a data table.
You can convert your string into a Date object and then format it like this:
let jsonString = "2019-02-03T06:48:07";
// You should set your own timezone and options.
console.log(new Date(jsonString).toLocaleString('en-US', {hour12: false}))
For more information, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
The T is there because this is a standard ISO 8601 format. It makes it very easy to parse on the client side:
var myDate = new Date('2019-02-03T06:48:07')
With myDate you can then do whatever formatting you wish. Assuming you have another function to handle leading zeros, that could be something like:
var myFormattedDate = padLeft(myDate.getMonth() + 1, '0') + '-' +
padLeft(myDate.getDay(), '0') + '-'
myDate.getFullYear() + ' ' +
// etc
Note that your timestamp lacks any timezone information. With this code it will be interpreted on the client side in whatever the local timezone of the user is. If it is UTC time, then you can correct for this by adding either 'Z' or '+00:00' onto the timestamp before parsing in the Date constructor.
If you are able to add a library to assist, this all becomes much easier with moment.js:
myFormattedDate = moment('2019-02-03T06:48:07').format('MM/DD/YYYY HH:mm:ss');

Issue with date and time is conversation depending on local timezone

Hello today I encountered an issue with time stamp conversions.. In my web form I'm using an bootstrap-datepicker where users can pick date and time. Afterwards I convert those values with moment.js to unix timestamp and pass it to PHP page. In the PHP page if the user is in different country the value is different and in the end in database is inserted wrong value.
So it's like the server timezone is Latvia/Riga GMT+2 and user from Georgia/Tbilisi has GTM+4. He's selecting start date 12.01.2017 15:00, Moment.js passes it to PHP page in the DB value of start date is inserted 12.01.2017 13:00.
Here is code from js
var start_date = $("#start_date").val();
var start_time = $("#start_time").val();
var start = moment.utc(start_date + ' ' + start_time, "DD.MM.YYYY HH:mm").tz("Europe/Riga");
afterwards var is passed via ajax to PHP script like start.unix()
In PHP it receives
$startDate = date('Y-m-d H:i:s', $_GET['start']);
And time is received by 2 hours earlier..
What can I do so the user selects time from anywhere on the world PHP inserts in DB as it selected correctly without timezone conversion.
You should never pass dates with timezones from client-to-server, always have the server be the boss in this case, otherwise you're inevitably going to have inconsistency issues in your database.
You either:
Always use UTC+0 dates.
Use keywords that represent a date (ie. yesterday, now, two days ago).
Using a keyword allows you to make the server decide which date do you want based on UTC+0 timezone.
TL;DR;
Always use UTC+0 datetimes and convert them server/client-side (it's your preference) depending on which timezone a user is on.
You can use following JS to get Client Timezone in JS:
var time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var start_date = $("#start_date").val();
var start_time = $("#start_time").val();
In PHP:
function getDateTime($start_date, $start_time, $time_zone) {
$dateTime = $start_date . ' ' . $start_time;
$date = new DateTime($dateTime, new DateTimeZone($time_zone));
$serverTimeZone = date_default_timezone_get();
$date->setTimezone(new DateTimeZone($serverTimeZone));
return $date->format('Y-m-d H:i:sP');
}
This might help you to sync timezone

How to insert moment JS time into MySQL

//In Node/JS
myDate = moment(data.myTime.format('YYYY/MM/DD HH:MM:SS')).toISOString();
//myDate shows '2014-09-24T04:09:00.000Z'
Insert INTO (dateColumn..) Values(myDate)...
This is the error I get after inserting, note column in Mysql is a "datetime" type.
MySQL Error:: { [Error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: '2014-09- 24T04:09:00.000Z' for column '_dateColumn' at row 1]
code: 'ER_TRUNCATED_WRONG_VALUE',
This result happens because you are using the toISOString() method and it is not a valid format to insert into your DATETIME column. The correct format probably is YYYY-MM-DD HH:MM:SS(I think it depends on MySQL configuration, but this is the default) as the docs points out.
So you should try using moment's format() method like this:
myDate = moment(data.myTime.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
In fact, I don't know what data.myTime is, but if its a moment object too, you can change the first format() method and remove the second one.
DontVoteMeDown answer is right, except that the minutes 'mm' and seconds 'ss' need to be in lowercase, otherwise a wrong value is returned:
myDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
Also, you should check the value sent by javascript before to do your SQL query, in PHP:
DateTime::createFromFormat('Y-m-d H:i:s', $myDate);
Will return false if the date is misformatted.
Here's a function extension to format it into the MySQL DateTime format
moment.prototype.toMySqlDateTime = function () {
return this.format('YYYY-MM-DD HH:mm:ss');
};
You'll be able to do: moment().toMySqlDateTime();
(I'm working with Node.js, Express and MySql and this has worked for me:)
var momentDate=new moment('2018-08-31T20:13:00.000Z');
var readyToInsert=momentDate.format("YYYY-MM-DD HH:mm:ss");
To generate mysql format datetime you can use this:
var moment = require('moment');
let currentTimestamp = moment().unix();//in seconds
let currentDatetime = moment(currentTimestamp*1000).format("YYYY-MM-DD HH:mm:ss");//mysql datetime.
currentTimestamp = moment(currentDatetime).valueOf();//current timestamp in milliseconds
moment().format("YYYY-MM-DD HH:mm:ss")
I think this is the correct format. Otherwise you get the months inserted in your minutes, and you also get seconds above 60.
myDate = moment(data.myTime.format('YYYY/MM/DD HH:MM:ss')).format("YYYY-MM-DD HH:MM:SS");
Tested in Chrome with Moment.js 2.9.0

Javascript date string conversion

I have a system that returns a JSON object that contains dates in string format.
These dates are in the format "2012-10-19 06:05:38 GMT" (no... I'm stuck with them like this)
So I need to get this into a date object (d) ready to output as d.toLocaleDateString()
In chrome it works perfectly by just passing the string to a new Date (Bad bad Chrome - makes Eric lazy), but of course it fails in FF and IE
I can fix it by splitting the string but its not pretty and I've not figured out dealing with the offsets from GMT.
There must be a more elegant way...?
I'm sure someone here can do it in one line.
It's not quite a one-liner, but if you know all your dates will be GMT, something like the following should work:
function parseDate(dateString) {
// [y, m, d, hr, min, sec]
var parts = dateString.match(/\d+/g);
// Months are 0-indexed
parts[1] -= 1;
return new Date(Date.UTC.apply(Date, parts));
}
If I were you, and had access to the serverside script gathering that information (and outputting it) I would convert the date into a unix timestamp, and then make Javascript process that using the Date constructor easily.
EDIT: You can use strtotime() function to convert the string date into numeric unix timestamp if you're using PHP.
If you know the exact format, you could use a library such as Moment.js: Documentation for Moment.js.
To parse:
var dateString = "2012-10-19 06:05:38 GMT".replace(" GMT", "");
var date = moment(dateString, "YYYY-MM-DD HH:mm:ss");
You can just parse the dateString manually,and pass the Date the Date constructor exactly:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
var dateString = "2012-10-19 06:05:38 GMT".split(" "),
date = dateString[0].split("-"),
time = dateString[1].split(":");
var dateObj = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);

javascript : how to get 'utc date'

I have a date in this string format "02/28/2012" and I want to convert it to UTC.
I'm using the jquery datepicker to select thedate and populate an inputbox. any clues?
Thanks
var datestr = "07/08/2005";
var datearr = datestr.split("/")
var utc = Date.UTC(datearr[2],datearr[0],datearr[1]);
var utcdate = Date.UTC(2012,2,28);
The other answers are good, but they will give you the wrong result.
In Javascript, the month argument is zero-indexed, so make sure to subtract 1 from the standard month number,
var utcms = Date.UTC(2012,2-1,28);
Unfortunately jquery .datepicker.parseDate(str) injects a local timezone (it would be nice if the documentation said this), and Date(str) and Date.parse(str) appear unpredictable about their treatment of local vs UTC.

Categories

Resources