Formatting a date string in javascript for SQL insertion - javascript

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];
}

Related

javascript function to accept multiple date formats

Users want to use the following formats to enter dates:-
mm-dd-yyyy OR yyyy-mm-dd OR m-d-yy OR m-d-yyyy OR mm/dd/yyyy OR m/d/yy.
My plan is to capture whatever they enter and convert it to yyyy-mm-dd because that is the format that the date field value must be submitted. They have refused to use a calendar . I have tried the following JS function without any success. Any ideas?
var value = ctrl.getValue();
var date_input = new Date(value);
var day = date_input.getDay();
var month = date_input.getMonth() + 1;
var year = date_input.getFullYear();
var yyyy_MM_dd = year + "-" + month + "-" + day;
return yyyy_MM_dd
Because its wrong to use var day = date_input.getDay();
use it like this
var day = date_input.getDate();
function getDateFormat(value){
var date_input = new Date(value);
var day = date_input.getDate();
var month = date_input.getMonth() + 1;
var year = date_input.getFullYear();
var yyyy_MM_dd = year + "-" + month + "-" + day;
return yyyy_MM_dd;
}
console.log(getDateFormat("2017-12-30"));
console.log(getDateFormat("12-30-2017"));
.getDay is giving you days of weeks
Also be sure to use date format accepted by Date

JavaScript date to MySQL datetime conversion

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);
}

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>'))

Save excel file with current date and time through javascript

I want to open the excel file and then save the excel file and the name will be file name + current date and time. I am not getting this result for date I have used Date()
var wshell;
var excel = new ActiveXObject("Excel.Application");
alert(excel);
var excel_file = excel.Workbooks.Open("book2.xlsx");
excel.Visible = true;
var objWorkbook = excel.Workbooks.Add();
var objWorksheet = objWorkbook.Worksheets(1);
objWorkbook.Worksheets(1).Activate;
objWorksheet.name = "test";
objWorksheet.Paste;
objWorksheet.columns.autofit;
window.clipboardData.setData("Text","");
var today = new Date();
document.write(today.toString());
excel_file.SaveAs("d:\\board.xls"+ (today.toString()));
alert("data saved");
today contains an illegal character (:) to use in a file name. You need to clean your date, for example something like this:
var today = new Date().toString().replace(/[^\w]/g, '');
And when saving, the timestamp should be a part of the file name instead of the extension:
excel_file.SaveAs("D:\\board" + today + ".xls");
Instead of .toString().replace() you can format the timestamp to look like you want with methods of Date object.
EDIT
Here's the code with which you can modify your dates. I've simplified getDate() for you, hence you can modify it to return a date in what ever form you want.
var today = new Date(),
time = today.toTimeString().split(':').join('').substr(0, 4),
timestamp = getDate('dd_mm_yyyy', today) + '_' + time;
function getDate (mode, userdate) {
var dte = userdate || new Date(),
d = dte.getDate().toString(),
m = (dte.getMonth() + 1).toString(),
yyyy = dte.getFullYear().toString(),
dd = (d.length < 2) ? '0' + d : d,
mm = (m.length < 2) ? '0' + m : m,
yy = yyyy.substring(2, 4);
switch (mode) {
case 'dd_mm_yyyy': return dd + '_' + mm + '_' + yyyy;
case 'yyyymmdd': return yyyy + mm + dd;
default: return dte;
}
}
timestamp contains a date in wanted form after run the code above.

Shorter way to write this JavaScript date code

Hello I want to get today's date in JavaScript in the following format: dd/mm/YYYY
The following code does the job but surely there is a shorter way to write this?
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var todaysDate = day + "/" + month + "/" + year;
Thanks in advance.
recommend a great js date/time lib: http://momentjs.com/
moment().format('D/M/YYYY'); //"10/2/2013"
if you need padding zeros:
moment().format('DD/MM/YYYY'); //"10/02/2013"
if you want write pure js, nothing much can do here, just cut off some variable.
var today = new Date;
//parenthesis around month is required.
var todaysDate = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();
//"10/2/2013"
Of course.
var date = new Date();
var todaysDate = date.getDate() + "/" + date.getMonth()+1 + "/" + date.getFullYear();
Note that this will return values without leading zeros. You can add them using one extra function for convenience:
function checkTime(i){if(i<10){i="0" + i}return i}
var date = new Date();
var todaysDate = checkTime(date.getDate()) + "/" + checkTime(date.getMonth()+1) + "/" + date.getFullYear();
Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask. Yours is quite simple enough.
You could use an external library, but the script size trade-off won't be optimal for just one simple operation.
A shorter version would be to combine the last 4 lines inline this way:
var today = new Date();
var todaysDate = today.getDate() + "/" + (today.getMonth()+1) + "/" + today.getFullYear();

Categories

Resources