On ASP.net MVC application where I save the date on datetime
field in SQL sever db.It saves like this 2015-04-22 18:43:18.967
.So now I need to show it as MST (Mountain Standard Time)
on client side.So how can I do that ? I can use Moment.js
or any other JavaScript library for that.Thanks in advance.
Asked
Active
Viewed 4,336 times
0

Sampath
- 63,341
- 64
- 307
- 441
-
Which timezone is your date saved in? – Tatermelon May 11 '15 at 18:30
-
From the datetime field from SQL, is it a string? Or is it a date object that you can run methods from? i.e., can you do datetime.getDate()? – ChadF May 11 '15 at 18:33
-
@Tatermelon I didn't specify any time zone.But I think it takes the default of sql server (may be `GMT`). – Sampath May 11 '15 at 18:34
-
@ChadF `Data Type = datetime` on Sql server. – Sampath May 11 '15 at 18:35
-
1@Sampath - In most cases, you should be storing UTC time in the database, but that depends entirely on how you obtained the time to begin with. Please read [The Case Against `DateTime.Now`](http://codeofmatt.com/2013/04/25/the-case-against-datetime-now/). – Matt Johnson-Pint May 12 '15 at 00:27
2 Answers
3
If you send the timestamp to the client and you are using momentjs, then it's pretty simple
var day = moment(TS_IN_MILLISECONDS).tz('America/Denver')
With the string you provided, you can do this:
var UTCTime = moment.utc('2015-04-22 18:43:18.967').toDate();
var MSTTime = moment(UTCTime).tz('America/Denver').format('YYYY-MM-DD HH:mm:ss');

Tatermelon
- 489
- 2
- 10
-
At this moment I'm showing this on client `2015-04-22 18:43:18.967`.So how can I apply above to this datetime ? – Sampath May 11 '15 at 18:45
-
Actually I think you can just pass that string instead of the timestamp. I'm just not certain it will process it as UTC time. – Tatermelon May 11 '15 at 19:12
-
I updated my answer with how to use the time string you are returning. – Tatermelon May 11 '15 at 19:22
0
So this will depend on what local time your server is running in (or if it's just pulling UTC it'll be a bit easier). But you can yank the timezone offset like this: dateTime.getTimezoneOffset()
, modify it it to reflect the offset difference between your server's timezone and MST. And then modify your original datetime to reflect the new offset.
This may be a good post for reference.
Also refer to here:
dateTime.setTime( dateTime.getTime() + dateTime.getTimezoneOffset()*[math to adjust your timezone] );