0

I have a JavaScript Date which I want to get it into SQL Server datetime field.

The JavaScript time sent over as

Fri Sep 15 2017 00:11:44 GMT-0700 (US Mountain Standard Time)

I want it to be converted in javascript or in C#

  1. I need the date to be like

    2017-09-15 23:47:01 
    

OR perhaps

9/15/2017 11:47:01 PM
  1. I need to also convert it to UTC , not sure if that is easier to do in javascript or in C#

Which type of format is my code even in? "Fri Sep 15 .." ??

For UTC I was seeing code like this

 var isoDate = new Date('yourdatehere').toISOString();

( I am doing .net core web api, with Angular 4 / Typescript)

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • I know it may seem trivial but working with dates and times is really hard, I recommend you leave it up to [moment.js](https://momentjs.com/) to handle this for you. If you remove "(US Mountain Standard Time)" from the string, it should be pretty easy. – kyle Sep 18 '17 at 23:19
  • Here is a simple regex, that basically extracts the bit's of an ISOString -> `new Date('Fri Sep 15 2017 00:11:44 GMT-0700 (US Mountain Standard Time)').toISOString().replace(/(^\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})(.*)$/,'$1 $2')` – Keith Sep 18 '17 at 23:38
  • But that creates `2017-09-15T07:11:44.000Z` –  Sep 18 '17 at 23:49

1 Answers1

0

As Keith said, working with dates is really hard in javascript, especially considering very different implementations across the browsers. So I will second their opinion: just use moment.js and leave everything to that library. It is really powerful. Using it you can get any date format you can possibly think of. To get "2017-09-15 23:47:01" all you need is the following (please pay attention that qualifiers are case sensitive!):

var fmt = moment(<your_js_date_if_you_have_it>).format("YYYY-MM-DD HH:mm:ss");

You can find all supported qualifiers here.

Apart from formatting this library also allows you to do a lot of manipulations with the dates, compare them, translate dates from local to UTC time zone and back, etc.

Alexander Leonov
  • 4,694
  • 1
  • 17
  • 25
  • I cannot use moment.js ... sadly a security team rejects 99% of packages... I've used it in the past. –  Sep 19 '17 at 00:33
  • Wow... Someone has even more restrictive security rules then me... Well, then the only viable option you have is to write something like moment.js yourself, but that's going to be a BIG pain - I've tried... :( – Alexander Leonov Sep 19 '17 at 00:42