convert date time to utc format - javascript

I have to convert local date and time to utc format.
Therefore if I have date as 2021-08-11 (YYYY-MM-DD) and time as 2:40 PM, then slot date time should be 2021-08-11T09:10:00.000Z.
I have tried multiple things, but failed
const dateTimeInUTC = moment(
`${formattedDate} ${formatTime}`,
'YYYY-MM-DD HH:mm:ss'
).toISOString();
above code resulted me => 2021-08-10T21:10:00.000Z (which is +5:30 more)
Also, tried following
const formatted = formattedDate + " " +formatTime (2021-08-11 02:40 PM)
const result = new Date(formatted).toISOString();
this gave me
Range error :Invalid Date
However, this works as expected in console, but gives error in mobile.

I tested it now, convert - to / in date format then it will work fine in react native both on browser console and mobile. for more info you can check that link
var isoDateString = new Date('2021/08/11 12:00 pm').toISOString();
console.log(isoDateString);
If you want to use your date format (date witn -) then you to add T instead of space and the time should be on 24 hour scale
like
var isoDateString = new Date('2021-08-11T13:00').toISOString();
this solution will also work for you.
thanks

you can try that
var isoDateString = new Date('2021-08-11 2:40').toISOString();
console.log(isoDateString);

If you want to covert current System Time to UTC then Do :
const dateTimeInUTC = new Date().toUTCString();
console.log(dateTimeInUTC);
Or if you want convert any specific Date-Time to UTC then Do :
const dateTimeInUTC = new Date("October 13, 2000 00:45:00").toUTCString();
console.log(dateTimeInUTC);

Related

Issues parsing a string-date React/JS

For example, I have this string "2020-09-09T21:00:14.114-04:00"
I grab this from my database and in its current form, it is a string. my goal is to have it display
4 PM instead of the long string of jibberish
is it possible to accomplish this?
I was thinking of possibly creating a new date object like
let test = new Date('2020-09-09T21:00:14.114-04:00').
but I'm stuck at the parsing and formatting part. it would be better to have this be done while the current state is a string but I don't think that this would be possible
edit: i would like the desired output to be the hour:minute and then am/pm
ex 10:15pm
You can do that by parsing the date from your database using Date.parse().
Then you can get the time or whatever you need using date.toLocalTimeString() in your case.
let dateUnix = Date.parse('2020-09-09T21:00:14.114-04:00');
const time = new Date(dateUnix).toLocaleTimeString();
console.log(time); // --> "4:00:14 AM"
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Here's some useful resources MDN Date.parse()
MDN Date.toLocalTimeString()
You can do as following way.new Date() is used to get the current date and time.
var today = new Date();
var time = today.getHours();
if(time>12){
var new_time= time % 12;
}
else{
var new_time= time;
}

How to create Date on server(there utc timezone) and correct display on client?

We escape of using moment now and use date-fns instead. In some places we still use moment on front.
Example of code on server
//date in yyyy/mm/dd format in query params
startOfDay = StartOfDay(new Date(date));
return startOfDay
And when I display this date on front, she changes to local timezone(-4 hours). If i use date-fns-tz and convert to Canada timezone, I will get date with -4 hours and after display -4 hours more. How to resole this issue? I need to add 4 hours to date for my current timeZone. My utcOffset = 4.
Although I am not sure what function your are currently using from date-fns-ts, what has worked for me is to use utcToZonedTime(). This function gets
a date/time in the local time of any time zone from UTC time
import { utcToZonedTime } from 'date-fns-tz'
const now = new Date() // UTC
const nowCustomTimeZone = utcToZonedTime(now, 'Europe/Amsterdam')

Express time as CST in javascript - date-fns

I am using date-fns to format dates
If I pass a date that ends in Z, it knows that it is UTC, and I can format(date, "yyyy-MM-dd") and it will be in local computer time.
If the date I want to express in local computer time is originally CST, is there something to add at the end instead of the Z, that will be understood by the format function as a CST date?
Sorry if this is a bad question
Edit: is there a way to do zonedTimeToUtc(myDate, 'UTC-6') in date-fns? (instead of using a time zone name)
If you have a string that you always want parsed as CST (US central standard time) using date-fns, you can include date-fns-tz and set the timezone when parsing (I've assumed an ISO 8601 loose format without the timezone). Note that to avoid DST, you have to pick a location that is UTC-6 all year round, e.g. Canada/Saskatchewan.
// Setup
var {parse} = require('date-fns');
var {zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz');
// Parse using location for offset
let loc = 'Canada/Saskatchewan';
let s = '2020-08-14 13:05:52';
let fIn = 'yyyy-MM-dd HH:mm:ss';
let utcDate = zonedTimeToUtc(s, loc);
// Show local equivalent
console.log(utcDate);
This leaves you somewhat at the mercy of the administrators of Saskatchewan, who might change the offset or introduce DST. An alternative is to append the exact offset you want to the timestamp and include it in the parse tokens:
// Parse using string for offset
let tz = '-06';
let utcDate2 = parse(s + ' ' + tz, fIn + ' X', new Date());
// Show local equivalent, should be same as above
console.log(utcDate2);
The advantage of the second method is that it doesn't require date-fns-tz and you aren't beholden to historic or future changes to Saskatchewan's offset (or that of any other IANA location).
Apparently there is a UTC module in development that will allow setting specific offsets like -6 rather than using IANA locations (can't find a link to that comment atm).
At this point the string has been parsed as GMT-6, but is still just a plain Date (i.e. just a time value with no idea of the timezone that was associated with the original string).
Once you have the date you can then show it as CST for output. To use an IANA location for the offset in call to format, you have to use format from date-fns-tz, not plain date-fns, otherwise it will just use the host system offset.
Note that the value in the format call is just setting the value to use for the offset string, it doesn't do anything to the actual date and time, that adjustment has already been applied by utcToZonedTime.
// Adjust to CST
let dCST = utcToZonedTime(utcDate2, loc);
// Format strings:
let fOut1 = 'yyyy-MM-dd HH:mm:ss XXX'; // -0600
let fOut2 = 'yyyy-MM-dd HH:mm:ss z'; // CST
// Format using location
console.log(format(dCST, fOut1, {timeZone: loc}));
console.log(format(dCST, fOut2, {timeZone: loc}));
I prefer the -0600 version as it avoids questions of whether DST is observed or not (and is really what the code is doing). Also, in the "z" version you might get the offset or the timezone name (probably depending on the host default language and location, which is a quirk of date-fns-tz using Intl.DateTimeFormat I think).
You can also manually add the timezone using a format string like:
let fOut = 'yyyy-MM-dd HH:mm:ss \'-0600\'';
which will produce an output like:
"2020-08-14 13:05:52 GMT-0600"
I don't think there is any way to set a specific offset like "-0600" for both parsing and formatting without including it in the call. I think moment.js and luxon allow it.
For completeness, here's some code you can run at npm.runkit.com since there's no CDN for the current date-fns version to allow the code to run here.
var {parse} = require('date-fns');
var {zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz');
// Parse using location for offset
let loc = 'Canada/Saskatchewan';
let s = '2020-08-14 13:05:52';
let fIn = 'yyyy-MM-dd HH:mm:ss';
let utcDate = zonedTimeToUtc(s, loc);
// Show local equivalent
console.log(utcDate);
// Parse using string for offset
let tz = '-06';
let utcDate2 = parse(s + ' ' + tz, fIn + ' X', new Date());
// Show local equivalent, should be same as above
console.log(utcDate2);
// Format using location:
let fOut1 = 'yyyy-MM-dd HH:mm:ss XXX'; // -0600
let fOut2 = 'yyyy-MM-dd HH:mm:ss z'; // CST
let dCST = utcToZonedTime(utcDate2, loc);
console.log(format(dCST, fOut1, {timeZone: loc}));
console.log(format(dCST, fOut2, {timeZone: loc}));
Try using moment libraries to solve your time problems: moment.js, and its complement moment-timezone.js
To output the current time converted to CST timezone:
moment().tz('America/Chicago').format('hh:mm:ss z')
06:43:34 CST
moment().tz('America/Chicago').format('hh:mm:ss z Z')
06:43:35 CST -06:00
moment().tz('America/Chicago').format()
2020-08-13T15:52:09-06:00
Or maybe use a function as below:
const calcTime = (cityOffset) => {
var now = new Date();
// convert to msec and add local time zone offset and get UTC time in msec
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
// create new Date object for different city using supplied offset
var newTime = new Date(utc + (3600000 * cityOffset));
return newTime.toLocaleString();
}

How to get difference between dates in different timezones using moment?

I'm using momentJS to get difference between 2 dates. Here is my code:
const createdAt = "2019-11-15 09:45:21"; // Sample data from mysql database
// Add time since created
const created = moment(createdAt);
const now = moment();
// get the difference between the moments
const diff = now.diff(created);
//express as a duration
const diffDuration = moment.duration(diff);
const days = diffDuration.days().toString().padStart(2, 0);
const hours = diffDuration.hours().toString().padStart(2, 0);
const minutes = diffDuration.minutes().toString().padStart(2, 0);
With that code, I can properly get the days, hours and minutes difference. The server where mysql is installed is in the Philippines and the createdAt value is automatically generated by mysql.
Now when I try to change my PC's timezone, I get incorrect date difference. I get negative values.
I tried doing something like adding utc():
const created = moment.utc(createdAt);
const now = moment.utc();
And I still don't get any correct values. Am I missing something? Is it possible to do this? Thanks in advance.
The createdAt time above is not UTC format so you will need to update the value by adding/subtracting the hours from your local time, or utc time. It's best to convert the relevant dates to UTC and then perform your diff from there.
Take a look at the options below for parsing and values:
// utc time now
const utcTime = moment.utc();
console.log(utcTime.toString());
// time recorded at server
const philliTime = moment('2019-11-15 09:45:21', 'YYYY-MM-DD HH:mm:ss');
console.log(philliTime.toString());
// need to add 8 hours as philli is +8 hours
philliTime.add(8, 'h');
console.log(philliTime.toString());
// options using parseZone
const optionBPhilli = moment.parseZone('2019-11-15 09:45:21 +08:00', 'YYYY-MM-DD HH:mm:ss ZZ');
console.log(optionBPhilli.toString());
const optionBUTC = moment.parseZone('2019-11-15 09:45:21 +00:00', 'YYYY-MM-DD HH:mm:ss ZZ');
console.log(optionBUTC.toString());
console.log(optionBPhilli.diff(optionBUTC, 'h'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
For more info on parsing the string, check the moment docs and also look at UTC parsing.

Convert (YYYY/MM/DD HH:MM:SS.MS) GMT to local time using JavaScript

For some reason, the SOAP response from one of my WebService looks like this:
2010/07/08 04:21:24.477
Where the date format is YYYY/MM/DD and the time is GMT.
I'm not really sure how to convert this to local time because the format is so odd.
Date.parse should actually parse most of the date string into its respective timestamp.
The 2 caveats appear to be:
Milliseconds aren't supported, so they have to be separated and added after parsing.
It'll assume local time, so 'GMT' or 'UTC' should to be appended before parsing.
With these in mind, the following should work:
function parseSoapDate(dateString) {
var dateParts = dateString.split('.'),
dateParse = dateParts[0],
dateMilli = dateParts[1];
return new Date(
Date.parse(dateParse + ' GMT') +
parseInt(dateMilli, 10)
);
}
var date = parseSoapDate('2010/07/08 04:21:24.477');
As for UTC to local time, JavaScript's Date objects should already handle that for you as they can report the date in both UTC and the user's local timezone. You specify which you want by the name of the method (whether it has UTC in it or not):
alert(date.toString()); // local time
alert(date.toUTCString()); // UTC time
This should work:
var dateStr = "2010/07/08 04:21:24.477";
var d = new Date(dateStr.split('.')[0]);
d.setUTCHours(0);
my JSON returns: YYYY-MM-DD HH:MM:SS, localization will work only on selected browsers Date.prototype.toLocaleDataString("en-us"[,option] )
function stringToDate(s) {
var language = window.navigator.userLanguage || window.navigator.language;
var options = {year: "numeric", month: "numeric", day: "numeric"};
s = s.split(/[-: ]/);
d = new Date(Date.UTC(s[0], s[1]-1, s[2], s[3], s[4], s[5]));
return d.toLocaleDateString( language , options)+" "+d.toLocaleTimeString();
}
// return
// Friday, November 15, 2013 2:21:04 PM --> FF25
// 11/15/2013 2:21:04 PM --> Chrome31
It looks like the response of the date/time is in ISO format, which is a sensible way to provide date information.
Suppose that the date returned is 7-8-2010. Would this be the 8th of July or the 7th of August? Having the date in ISO format (YYYY/MM/DD) solves this ambiguity.
You can convert this date to the required format in many different ways, i.e.
var input = '2010/07/08 04:21:24.477';
var now = new Date(input.slice(0, input.indexOf('.')));
alert(now.toLocaleString());
You may want to search the Internet for the Date object or to find snippets which will allow you to convert a date using many different formats.

Categories