Javascript date to sql date object - javascript

I'm trying to write a query that takes a Javascript date object and then puts it in an object type that is recognized by both SQL Server and Oracle database types.
The issue is that I'm using webservices. So it has to be a string, not an actual passed parameter. Here's what I mean:
var date = new Date();
var firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var webServicesQueryWhereClause = 'readDate BETWEEN '+firstDayOfMonth+' AND '+lastDayOfMonth;
Except firstDayOfMonth and lastDayOfMonth are surrounded by something like to_date() to actually put them in a date format that the databases can read. For example:
var webServicesQueryWhereClause = 'readDate BETWEEN to_date('+firstDayOfMonth+') AND to_date('+lastDayOfMonth+') ';
What should I use to put those dates in a form that can be read by both SQL Server and Oracle?

Have you tried the solutions presented here:
Convert JS date time to MySQL datetime
The title should be called
"Convert JS date to SQL DateTime"
I happened to need to do the same thing as you just now and I ran across this after your question.
This is from the other post by Gajus Kuizinas for those who want the answers on this page:
var pad = function(num) { return ('00'+num).slice(-2) };
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
pad(date.getUTCMonth() + 1) + '-' +
pad(date.getUTCDate()) + ' ' +
pad(date.getUTCHours()) + ':' +
pad(date.getUTCMinutes()) + ':' +
pad(date.getUTCSeconds());
or
new Date().toISOString().slice(0, 19).replace('T', ' ');
The first one worked for me. I had a reference problem with the toISOString as well although I would prefer the one liner. Can anyone clarify how to use it and know the limitations on where one can reference it?
Good luck!

using MomentJs it will be pretty easy.
moment().format('YYYY-MM-DD HH:mm:ss')
https://momentjs.com/

In my case I was trying to get a TIMESTAMP and store it to a variable so I can pass that array inside a SQL query(Row insertion)
The following worked for me quite well.
var created_at = new Date().toISOString().slice(0, 19).replace('T', ' ');

Maybe I found a bit shorter approach - tested on MSSQL and Postgres
const date = (new Date()).toLocaleString("en-US")
Enjoy!

I use:
const datetimeSQL = new Date().toISOString().split('T').join(' ').split('Z').join('');
// return '2022-09-02 19:54:17.028'

Related

How do I convert UTC DateTime to local DateTime without ending up with a different format

I have specific DateTime values in this format 'YYYY-MM-DDThh:mm:ss.ms' (e.g. '2022-05-10T13:44:00.0000000') and I need to convert them to local DateTime (which is UTC+2 for me) without changing the format (so '2022-05-10T15:44:00.0000000' is the desired result (even better would be without the milliseconds but that would just be the icing on the cake)).
I've searched far and wide but every alleged solution I find either changes the format or doesn't change the time at all.
This is what I have right now, it successfully converts the time to local time but by running it through .toISOString() to get the original format back it converts it back to UTC time.
//Input: event.start.dateTime = '2022-05-10T13:44:00.0000000'
let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() -
startDateTime.getTimezoneOffset());
document.getElementById('ev-start').value =
startDateTime.toISOString().slice(0,16);
//Output: '2022-05-10T13:44:00.000Z'
I couldn't find a clean and satisfying solution so I decided to just to the formatting myself. Here's what I ended up with:
Input: '2022-05-10T13:44:00.0000000'
let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() -
startDateTime.getTimezoneOffset());
let localStartDateTime = startDateTime.getFullYear() + "-" +
(startDateTime.getMonth() + 1).toString().padStart(2, '0') +
"-" + startDateTime.getDate().toString().padStart(2, '0') +
"T" + startDateTime.getHours().toString().padStart(2, '0') +
":" + startDateTime.getMinutes().toString().padStart(2, '0')
+ ":" +
startDateTime.getSeconds().toString().padStart(2, '0');
document.getElementById('ev-start').value =
localStartDateTime;
Output: '2022-05-10T15:44:00'
Hope this helps
const startDateTime = new Date('2022-05-10T13:44:00.0000000');
const outputDateTime = new Date(startDateTime.toString()).toISOString().slice(0, 19);
//document.getElementById('ev-start').value = outputDateTime
console.log(outputDateTime);

How to add days to javascript unix timestamp? [duplicate]

I want to convert date to timestamp, my input is 26-02-2012. I used
new Date(myDate).getTime();
It says NaN.. Can any one tell how to convert this?
Split the string into its parts and provide them directly to the Date constructor:
Update:
var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
Try this function, it uses the Date.parse() method and doesn't require any custom logic:
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
this refactored code will do it
let toTimestamp = strDate => Date.parse(strDate)
this works on all modern browsers except ie8-
There are two problems here.
First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.
Second, you need to pass it a string in a proper format.
Working example:
(new Date("2012-02-26")).getTime();
UPDATE: In case you came here looking for current timestamp
Date.now(); //as suggested by Wilt
or
var date = new Date();
var timestamp = date.getTime();
or simply
new Date().getTime();
/* console.log(new Date().getTime()); */
You need just to reverse your date digit and change - with ,:
new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)
In your case:
var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();
P.S. UK locale does not matter here.
To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k...
I had to devide it by 1000:
new Date('2012-02-26').getTime() / 1000
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
For those who wants to have readable timestamp in format of, yyyymmddHHMMSS
> (new Date()).toISOString().replace(/[^\d]/g,'') // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"
Usage example: a backup file extension. /my/path/my.file.js.20190220
Your string isn't in a format that the Date object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29) before asking Date to parse it.
Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns NaN.
JUST A REMINDER
Date.parse("2022-08-04T04:02:10.909Z")
1659585730909
Date.parse(new Date("2022-08-04T04:02:10.909Z"))
1659585730000
/**
* Date to timestamp
* #param string template
* #param string date
* #return string
* #example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
The below code will convert the current date into the timestamp.
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
The first answer is fine however Using react typescript would complain because of split('')
for me the method tha worked better was.
parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))
Happy to help.
In some cases, it appears that some dates are stubborn, that is, even with a date format, like "2022-06-29 15:16:21", you still get null or NaN. I got to resolve mine by including a "T" in the empty space, that is:
const inputDate = "2022-06-29 15:16:21";
const newInputDate = inputDate.replace(" ", "T");
const timeStamp = new Date(newInputDate).getTime();
And this worked fine for me! Cheers!
It should have been in this standard date format YYYY-MM-DD, to use below equation. You may have time along with example: 2020-04-24 16:51:56 or 2020-04-24T16:51:56+05:30. It will work fine but date format should like this YYYY-MM-DD only.
var myDate = "2020-04-24";
var timestamp = +new Date(myDate)
You can use valueOf method
new Date().valueOf()
a picture speaks a thousand words :)
Here I am converting the current date to timestamp and then I take the timestamp and convert it to the current date back, with us showing how to convert date to timestamp and timestamp to date.
The simplest and accurate way would be to add the unary operator before the date
console.log(`Time stamp is: ${Number(+new Date())}`)
Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:
var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000
Simply performing some arithmetic on a Date object will return the timestamp as a number. This is useful for compact notation. I find this is the easiest way to remember, as the method also works for converting numbers cast as string types back to number types.
let d = new Date();
console.log(d, d * 1);
This would do the trick if you need to add time also
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work without Time
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work but it won't Accept Time
new Date('2021/07/22').getTime()
And Lastly if all did not work use this
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Note for Month it the count starts at 0 so Jan === 0 and Dec === 11
+new Date(myDate)
this should convert myDate to timeStamp

Date.UTC() gets value null

From Server I get Date in UTC format like ,
2016-04-13T02:37:13.211316121-04:00
When I use this to display using new Date(data.Created_at) I get 7 min time difference. Like as I am displaying my date in format {{my_date | date: 'h:mm a'}}, insted showing 12:05 PM, it dispalys 11:58 AM. So I tried this,
data.Created_at = new Date(Date.UTC(data.Created_at))
which returns null value. Is there any problem in my code? How should I get perfect date?
If you check syntax of Date.UTC,
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
It expects value in different variables and not in date string. You can split it and manually parse it.
You can try something like this:
JSFiddle
var d = "2016-04-13T02:37:13.211316121-04:00";
var date_arr = d.split(/[-|T|\.|:]/);
var o = new Date(Date.UTC(date_arr[0], date_arr[1], date_arr[2], date_arr[3], date_arr[4], date_arr[5]));
console.log(date_arr, o);
Also, it gives me 8:07 AM, considering the time is 2:37 and my timezone is +5:30.
Use it like this
Date.UTC(year,month,day,hours,minutes,seconds,millisec)
The code you are using is invalid way to handle date. You can use this code
new Date('2016-04-13T02:37:13.211316121-04:00').toISOString();
var created_at = new Date(createdAt);
var created_at_date = (created_at.getUTCMonth()+1) + "/" + created_at.getUTCDate() + "/" + created_at.getUTCFullYear() + "/" + created_at.getHours() + ":"
+ created_at.getMinutes() + ":" + created_at.getSeconds();
Hope this will work for you!!!

Convert SQL datetime to string or Date object [duplicate]

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).
Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}
Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.
Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.
Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

Converting string to date object, adding two hours and converting back to string (JavaScript)

I have a date string, want to convert it into a date object, add 2 hours and print out the converted date object back to a variable. But I get the error listed bellow:
// dateTime: 2013-09-27 09:50:05
var dateTime = $("#inputDatetime").val();
var startDate = dateTime;
var date = new Date(startDate);
var duration = 2;
var endDate = date;
endDate.setHours(date.getHours()+duration)
var dateString = endDate.format("dd-m-yy hh:mm:ss");
Error:
Uncaught TypeError: Object [object Date] has no method 'format'
Why do I get this TypeError?
Vaibs,
there is no method "format", you can do formating using available methods from Date Object.
please don't use plugin
example :
// dd-mm-yy hh:mm:ss
function formatDate(date) {
return ((date.getDate()<10?'0':'')+date.getDate()) + "-"+
(((date.getMonth()+1)<10?'0':'') + (date.getMonth()+1)) + "-" +
date.getFullYear() + " " +((date.getHours()<10?'0':'')+date.getHours()) + ":" +
(date.getMinutes()<10?'0':'') + date.getMinutes() + ":" +
(date.getSeconds()<10?'0':'') + date.getSeconds();
}
*thank you #donot
Use jquery ui date parser.
http://docs.jquery.com/UI/Datepicker/parseDate
This is the best function for parsing dates out of strings that I've had the pleasure to work with in js. And as you added the tag jquery it's probably the best solution for you.
.format() is not a valid Date method. JavaScript does not have an easy way to format dates and times with a user-specified format. The best you can do (without separate plugins) is to create your own string by getting each component of the date separately, and formatting/concatenating them.
I've used this before and it seems to work!
var dateString = endDate.toString("dd-m-yy hh:mm:ss");

Categories

Resources