JavaScript date to MySQL datetime conversion - javascript

I have a js date variable
var date = "2017-01-23T10:17:50.285Z";
I have stored this in MySQL table and the column have type DATETIME
after storing in the database the value in the table looks like this:
Now when I am trying to get the record from the database using this column name I am doing like this:
var mysqlFormate = new Date(date).toISOString().slice(0, 19).replace('T', ' ');
which is giving the output as 2017-01-23 10:17:50
The problem
You can see the value stored in the database is different than the converted value (2017-01-23 15:47:50 and 2017-01-23 10:17:50 are different).
So I am not able to get the data from the database using this column.
What can be the possible mistake I am doing here? Thanks.

Check How you could set Time Zone information on SQL Server(or follow a convention).
in
new Date(date).toISOString().slice(0, 19).replace('T', ' ')
Replace the toISOString with formatLocalDate() with the below definition
function formatLocalDate() {
var now = new Date(),
tzo = -now.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
var norm = Math.abs(Math.floor(num));
return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear()
+ '-' + pad(now.getMonth()+1)
+ '-' + pad(now.getDate())
+ 'T' + pad(now.getHours())
+ ':' + pad(now.getMinutes())
+ ':' + pad(now.getSeconds())
+ dif + pad(tzo / 60)
+ ':' + pad(tzo % 60);
}
there's a clear 5h30m so I presume you're converting(or forgetting) the GMT to IST Offset.

In order to show the local time in JS there is Date.UTC() function it tells the browser that the date you're about to give it is expressed in UTC, that way, the browser will apply the required conversion and show it as local time.
function getLocalTime(mysqlDate) {
var dateTime = mysqlDate.split(' ');
var date = dateTime[0].split('-');
var time = dateTime[1].split(':');
var utc = Date.UTC(date[0], date[1], date[2], time[0], time[1], time[2]);
return new Date(utc);
}

Related

How to get time by this string in javascript 2017-11-29T10:27:15.2327188Z

I have this string 2017-11-29T10:27:15.2327188Z I just need to get time in javascript any idea how ?
First, convert the string into a date object:
var date = new Date('2017-11-29T10:27:15.2327188Z');
Then, you can call toLocaleTimeString() to return a string with a language sensitive representation of the time portion of this date:
console.log(date.toLocaleTimeString());
I believe this will get your local time from the string.
var x = '2017-11-29T10:27:15.2327188Z'
var d = new Date(x);
var time = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
console.log(time)

convert xml date and time using javascript

I am pulling the some information from a stock feed. the time stamp for last update comes in like this:
2016-02-10 13:32:41
How do I format it to be like:
1:32:41pm
2/10/2016
Here is my variable declaration:
time = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
You could turn the string into a valid javascript date and then use the date methods to display it how you want to. For example to turn it into a javascript date, split it into its parts and then assemble.
var dateAndtime = x[0].getElementsByTagName("LASTDATETIME")[0].childNodes[0].nodeValue;
var date = dateAndtime.split(' ')[0];
var time = dateAndtime.split(' ')[1];
var year = date.split('-')[0];
var month = date.split('-')[1]-1;
var day = date.split('-')[2];
var hour = time.split(':')[0];
var minute = time.split(':')[1];
var second = time.split(':')[2];
var d = new Date(year, month, day, hour, minute, second);
There is no need to create a Date, you can just parse and reformat the string. You have to parse the string anyway, reformatting without a Date is just more efficient.
// 2016-02-10 13:32:41 => m/dd/yyyy h:mm:ssap
function reformatDateString(s) {
var b = s.split(/\D/);
var ap = b[3] < 12? 'am':'pm';
var h = b[3]%12 || 12;
return h + ':' + b[4] + ':' + b[5] + ap +
'\n' + +b[1] + '/' + b[2] + '/' + b[0];
}
document.write(reformatDateString('2016-02-10 13:32:41').replace('\n','<br>'))
document.write('<br>');
document.write(reformatDateString('2016-12-09 03:02:09').replace('\n','<br>'))

Formatting a date string in javascript for SQL insertion

I am getting DATETIME strings in the following format from the facebook API:
2013-12-15T19:00:00-0800
I want to format this so I can properly insert it into an SQL date column. Below is the jist of the approach I've been taking. I am able to insert it into the database using these formatting techniques but when I try an SQL mechanism such as ORDER BY DATE it's not working.
var newDate = new Date('2013-12-15T19:00:00-0800').getTime() / 1000
Another approach:
var test = new Date('2013-12-15T19:00:00-0800')
//var newDate = new Date(test.getFullYear(), test.getMonth(), test.getDate());
Edit:
Below is a function showing some additional attempts at formatting the date as per the suggestions below. The order by hasn't worked for any of these approaches and the the returned type from the select statement is still "string".
function fbStampToDbDate(fbTimeOffSet){
if(fbTimeOffSet.indexOf('T') > 0){
var date = new Date(fbTimeOffSet.substring(0, fbTimeOffSet.indexOf('T')));
var fbStamp = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
var stamp = fbTimeOffSet.split("T");
}else{
var date = new Date(fbTimeOffSet);
var fbStamp = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
var stamp = fbTimeOffSet.split("T");
}
//return fbStamp;
return stamp[0];
}

Parsing the date in MM/DD/YY format

I get the response for the Date in this format while showing in the text box, how do i covert it to MM/DD/YYYY and Again re covert it to back to this format while sending
/Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}
Note, that month begins from 0.
To convert the regExp-like string to a real Date Object you could use:
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''))
, dat = new Date(dateNum); //=>Date {Wed May 25 2011 20:30:00 GMT+0200}
To display formatted dates I use my own small library, which may be of use to you.
var s = '/Date(1306348200000)/';
// convert to javascript date
var date = new Date(parseInt(s.substr(6, 13))); // removes /Date( & )/
// format the date
function pad(n) { return n < 10 ? '0' + n : n; } // leading zeros
var ddmmyy = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear().toString().substr(2);
// convert back
s = '/Date(' + date.getTime() + ')/';
here you can find everything regarding javascript dates http://www.w3schools.com/js/js_obj_date.asp

Converting DOMTimeStamp to localized HH:MM:SS MM-DD-YY via Javascript

The W3C Geolocation API (among others) uses DOMTimeStamp for its time-of-fix.
This is "milliseconds since the start of the Unix Epoch".
What's the easiest way to convert this into a human readable format and adjust for the local timezone?
One version of the Date constructor takes the number of "milliseconds since the start of the Unix Epoch" as its first and only parameter.
Assuming your timestamp is in a variable called domTimeStamp, the following code will convert this timestamp to local time (assuming the user has the correct date and timezone set on her/his machine) and print a human-readable version of the date:
var d = new Date(domTimeStamp);
document.write(d.toLocaleString());
Other built-in date-formatting methods include:
Date.toDateString()
Date.toLocaleDateString()
Date.toLocaleTimeString()
Date.toString()
Date.toTimeString()
Date.toUTCString()
Assuming your requirement is to print the exact pattern of "HH:MM:SS MM-DD-YY", you could do something like this:
var d = new Date(domTimeStamp);
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds(),
month = d.getMonth() + 1,
day = d.getDate(),
year = d.getFullYear() % 100;
function pad(d) {
return (d < 10 ? "0" : "") + d;
}
var formattedDate = pad(hours) + ":"
+ pad(minutes) + ":"
+ pad(seconds) + " "
+ pad(month) + "-"
+ pad(day) + "-"
+ pad(year);
document.write(formattedDate);
var d = new Date(millisecondsSinceEpoch);
You can then format it however you like.
You may find datejs, particularly its toString formatting, helpful.

Categories

Resources