0

For one of the records in my database we store two timestamps which represent the same moment in time.

One which is UTC such as this '2016-09-23 11:43:34.0000000'

And another that has a local time to the device that uploaded the data to the DB such as this '2016-09-23 06:43:34.0000000'.

Neither of these are stored with an offset due to the columns being datetime2. My question is, using either C# on my server or Javascript (such as moment.js) on my client app, would I be able to display the UTC timestamp in the users local time? From the client app I could get the current users time offset and do a calculation, I just don't understand which type of calculation I should do against the UTC timestamp.

I have looked at examples from this post Here, but have noticed the original datetime format they are using ('2015-02-05T07:52:27.59') is much different from mine.

Community
  • 1
  • 1
Stavros_S
  • 2,145
  • 7
  • 31
  • 75

3 Answers3

2

Here are various ways of parsing and converting utc time to local. I prefer the timezone variation.

var utcMoment = moment.utc('2016-09-23 11:43:34.3456789', 'YYYY-MM-DD hh:mm:ss.SSSSSSS').format('YYYY-MM-DD HH:mm:ss.SSS'));      

//Using Date
var localTime  = moment.utc(utcMoment).toDate().format('YYYY-MM-DD HH:mm:ss');
//Using local
var localTimeMoment  = moment.utc(utcMoment).local().format('YYYY-MM-DD HH:mm:ss');
//Using Timezone
var localTimeTz  = moment.utc(utcMoment).tz('America/Chicago').format('YYYY-MM-DD HH:mm:ss');
//Using Offset
var localTimeOffset = moment.utc(utcMoment).utcOffset('-05:00').format('YYYY-MM-DD HH:mm:ss');
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • One question, I notice your initial utc timestamp contains various numbers after the decimal, in my case it is always stored with .000000 in the DB. Would this have any large effect on your above results? – Stavros_S Sep 26 '16 at 14:09
  • i dont think its going to have any effect. please verify. – s7vr Sep 26 '16 at 14:12
1

use var date =new GetUTCDate(//any date);

you will get date in UTC formate

Alex
  • 818
  • 1
  • 8
  • 17
  • I already have a date in UTC, in the above example it's 2016-09-23 11:43:34.0000000 my question is how could I display this timestamp in the users local time when my UTC date does not have an offset. – Stavros_S Sep 26 '16 at 04:10
1

If want a c# solution you can use the DateTimeOffset Object. Specifically you will need to use the tryParse method which would allow you to print it in UTC.

If you prefer a js solution than going with moment tends to be a better option. I believe you need the moment().utcOffset() function to manipulate your current time stamp.