33

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?

6
  • 6
    All SQL databases can read the ISO date format unambiguously: ("YYYY-MM-DD HH:mm:ss") firstDayOfMonth.toISOString() should do the trick. Commented Nov 19, 2013 at 22:51
  • How is this being executed? Which library are you using? It's generally best to leave it up to the DB to decide how to translate a date object to a recognised format (however, that may not be possible in your case). Commented Nov 19, 2013 at 22:52
  • I'd suggest building the query string in your web service layer, unless this is node.js code. If you use asp.net, take a look at: momentjs.com/docs/#/parsing/asp-net-json-date Commented Nov 19, 2013 at 22:54
  • @James I'm using the atmosphere library and javax.jws server side to handle the web services. Commented Nov 19, 2013 at 22:57
  • @guiomie That's not an option. This query string being run from an app created with Sencha. Commented Nov 19, 2013 at 22:59

8 Answers 8

72

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!

Sign up to request clarification or add additional context in comments.

5 Comments

question was on MS SQL ( T-sql) not mysql :/
The first one worked for me, but it has a typo: for each "pad" there must be a closing of the function call, ie one ")".
Careful with toISOString: a same date can return different results according to your timezone and day time! Example: now is june 29 at 22:58 (UTC+2) and new Date(2023, 5, 29).toISOString() is returning 2023-06-28T22:00:00.000Z
As stated by Maxime up here, using "toSOString" will first convert your date into UTC so, in case you are using a different timezone in the database connection, the result might represent a wrong time. In other words, this is reliable only if you assume Node the database connection is UTC too. In my case, new Date().toISOString().slice(0, 19).replace('T', ' '); results in 2025-05-18 18:57:01 which is UTC, but then database expects CET so the result is incorrect.
7

using MomentJs it will be pretty easy.

moment().format('YYYY-MM-DD HH:mm:ss')

https://momentjs.com/

Comments

5

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

1 Comment

There's already a answer with this exact snipet
3

Slice off the .sssZ (milliseconds and Z UTC timezone) and replace the T with a space:

console.log(
  new Date().toISOString().slice(0, -5).replace('T', ' ')
)

Comments

2

Maybe I found a bit shorter approach - tested on MSSQL and Postgres

const date = (new Date()).toLocaleString("en-US")

Enjoy!

1 Comment

It doesn't work for me. The return value is "6/30/2021, 2:39:16 PM" while It needs to be of type "2021-06-30 2:39:16 PM".
2

Hopefully there is one country in the world that is sql friendly:

console.log(new Date().toLocaleString('lt-LT'));
// 2023-12-18 10:48:55

Hurray for Lithuania!

1 Comment

This should be the right answer or at least this should be considered as a possible solution.
1

I use:

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

2 Comments

I think new Date().toISOString().replace(/T/, ' ').replace(/Z/, '') would be more efficient.
Thanks @timkay, i'll try it the next time :+1
1

Here is the solution I came up with by combining several of the above answers.

const currentDate = new Date().toLocaleString('lt-LT').substring(0,10); this gives an output of YYYY-MM-DD HH:MM:SS, so I made a substring to cut off time which makes it comparable to sql date. then I used a simple greater than operator to compare the dates. For my use case, I needed to see if the sql date was today or later so I did this

events = //events array from db
const currentDate = new Date().toLocaleString('lt-LT').substring(0,10);
events = events.filter((event) => event.date >= currentDate)

This gave me an array of events that were either today or in the future.

2 Comments

Pardon me, but I don't understand how your answer is related to the question. The question asks how to convert JavaScript Date to a string that can be converted by both Oracle and SQL Server databases to a value having the DATE data-type. How is an array of events that were either today or in the future related? Also, isn't 'lt-LT' the locale for Lithuania? How is that related to the question?
@Abra I used the Lithuania locale because it outputs a string that very closely resembles a sql date. I mentioned that rationale in my answer. While my particular use case for needing the string wasn't strictly related to the OPs question, I included it to demonstrate a possible use for that date string. My code snippet creates a timestamp that needs very little change to make it comparable to the sql time format

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.