Convert date range object into ISO-8601 format using moment.js - javascript

I am using this react based date range picker. It gives me a setSelectedDayRange as an object of from and to like this
from: {day: 3, month: 8, year: 2020}
to: {day: 8, month: 8, year: 2020}
I need to convert the above into the ISO-8601 format. Since I already have moment.js installed in my project, I was hoping to utilize it.
The problem is
if I try to do it like
setSelectedDayRange = moment();
let convertedDate = moment().toISOString();
console.log("setSelectedDayRange", convertedDate);
It only converts the to date.
if I try to do it like
let convertedDate = moment(setSelectedDayRange).toISOString();
console.log("setSelectedDayRange", convertedDate);
It ends up converting currentDate-1
handleDatePickerChange = (setSelectedDayRange) => {
console.log("initializing handleDatePickerChange()");
console.log("setSelectedDayRange", setSelectedDayRange);
// TODO
// convert the dates
setSelectedDayRange = moment();
let convertedDate = moment().toISOString();
console.log("setSelectedDayRange", convertedDate);
// let convertedDate = moment(setSelectedDayRange).toISOString();
// console.log("setSelectedDayRange", convertedDate);
this.setState({
selectedDayRange: setSelectedDayRange,
});
};
Sandbox URL to mess around with it.

Ciao, if you need just to convert setSelectedDayRange to date in toISOString you could do:
let convertedDateFrom = moment(setSelectedDayRange.from).toISOString();
console.log("setSelectedDayRange", convertedDateFrom);
let convertedDateTo = moment(setSelectedDayRange.to).toISOString();
console.log("setSelectedDayRange", convertedDateTo);
Here your code modified.

Related

Javascript find time difference in hours with timezone

I have a javascript object with the following details:
var dateobj = {
date: "2020-12-21 03:31:06.000000",
timezone: "Africa/Abidjan",
timezone_type: 3
}
var date = new Date();
var options = {
timeZone: dateobj.timezone
};
var curr_date = date.toLocaleString('en-US', options)
console.log(curr_date)
//I want this
//diff = curr_date - dateobj.date
I want to find the time difference in hours with the current date-time of the same timezone. I know I can use toLocaleString() function to get the date-time string in a particular timezone, but how can I find the time difference? The above code gets the current date time in that timezone, how can I find the time difference in hours?
In general when working with dates in JS I usually use a library called date-fns (Date functions). It just makes dates and time a lot easier to manage. This is how you would get the time difference in hours with date-fns.
const { differenceInHours } = require("date-fns");
const { zonedTimeToUtc } = require("date-fns-tz");
const timeData1 = {date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3};
const timeData2 = {date: "2020-12-21 03:31:06.000000", timezone: "America/Los_Angeles", timezone_type: 3};
const t1 = zonedTimeToUtc(timeData1.date, timeData1.timezone);
const t2 = zonedTimeToUtc(timeData2.date, timeData2.timezone);
const diff = differenceInHours(t2, t1);
console.log(diff);
// => 8
Run demo: https://runkit.com/embed/jtfu0ixxthy7

Get timestamp from date string without timezone and timezone name apart

I have a dateTime string in this (bad, I know) format coming from an external API:
const startDate = '2/13/2020 15:00';
and the timezone name:
const timezoneName = 'America/New_York';
Which means that the dateTime is 2/13/2020 15:00 in New York.
Any idea for an elegant way to get timestamp (or JavaScript date object)?
I don't mind using moment.js or/and moment-timezone if it helps.
Moment and Moment-Timezone are for legacy code.
For new applications, the Moment team recommends Luxon.
const startDate = '2/13/2020 15:00';
const timezoneName = 'America/New_York';
const dateTime = luxon.DateTime.fromFormat(startDate, 'M/d/yyyy HH:mm',
{ zone: timezoneName });
const utcDateTime = dateTime.toUTC();
const s = utcDateTime.toISO();
console.log(s); //=> "2020-02-13T20:00:00.000Z"
Using moment-timezone should work:
const moment = require('moment-timezone');
const t = moment.tz("2/13/2020 15:00", "MM/DD/YYYY HH:mm","America/New_York");
console.log(t.toISOString()); // Prints '2020-02-13T20:00:00.000Z'

Why is the value output by MomentJS not reflecting UTC time?

I am trying to get a particular day/time in UTC format. Example code
const today = moment().tz('America/New_York')
const tomorrow = today.add(1, 'days')
const formatTime = today.format('YYYY-MM-DD')
const time = '7:00 pm'
const deliveryTime = moment(`${formatTime} ${time}`)
console.log(deliveryTime.utc().format())
Shouldn't I be getting this as output 2019-10-01T19:00:00Z as I am getting it on https://repl.it/#azs06/SilkyBronzeInversion
Suppose to 2019-10-02T13:00:00Z this on https://jsfiddle.net/azs06/hkrvze1x/2/
Is this is because of Node.js implementation of date?
What would be proper way to convert date time to UTC using moment.js?

Convert DateTime to Local Timezone - Sugarcrm Moment js

I am trying to change a specific datetime to user/local timezone datetime. But i couldnt able to convert it. I tried all possible solutions availabe for javascript and tried moment js. It still give me invalid date.
My DateTime Object:
{date: "2017-07-14 14:23:30.000000", timezone_type: 3, timezone: "UTC"}
What I am trying is to convert it to the user timezone or local timezone.
Is there any options available in Moment.js to do it?
In my SugarCRM JavaScript, I couldnt use Date.toUTC.
Methods I tried:
Convert UTC date time to local date time using JavaScript
// input data
var myDateTime = {
date: "2017-07-14 14:23:30.000000",
timezone_type: 3,
timezone: "UTC"
};
// Z in string and format in order to force UTC
var utcMoment = moment(myDateTime.date + "Z", "YYYY-MM-DD HH:mm:ss.SZ");
// convert to time zone of sugar user
var myDate = SUGAR.App.date.UTCtoLocalTime(utcMoment);
// format output
var localDateTime = myDate.format("YYYY-MM-DD HH:mm:ss");
Result:
localDateTime
"2017-07-14 16:23:30"
Found the solution with the help of #jay, did a few modifications and made it work for me.
var myDateTime = {
date: "2017-07-14 14:23:30.000000",
timezone_type: 3,
timezone: "UTC"
};
var myDate = SUGAR.App.date.UTCtoLocalTime(new Date(myDateTime.date));
// 2017-07-14 12:20:26
var resultDate = moment(myDate).format('YYYY-MM-DD HH:mm:ss');
// Mon, Jul 17, 2017 10:40 AM
var resultformat = moment(myDate).format('llll');

Json Stringify date produces a wrong date compared to javascript date

When i create a javascript date and then stringify it and send it to the server, i get two different dates. The stringified date is always one day behind.
So currently i increment my javascript date by 1 day so that i receive the same date on the server.
my current code:
var dt = $(.datepicker).datepicker('getDate');//Fri Aug 26 2016 00:00:00 GMT+0200 (South Africa Standard Time)
var result = Json.stringify(dt); //"2016-08-25T22:00:00.000Z"
Is this the correct approach or am i missing something?
This is due to the timezone component in the Date. The work around I did was:
var date = $(.datepicker).datepicker('getDate');
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()))
var result = Json.stringify(utcDate);
The removes the timezone component.
You don't seem to understand that both of your datetimes are actually the same and are correct. You haven't explained why you think that you need to manually alter the one sent to the server. Here is an example that demonstrates that they are in fact the same, just displayed in different formats in different timezones.
// Values from the local datetime string
var local = {
year: 2016,
month: 7,
day: 26,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Values from the UTC ISO 8601 datetime string
var utc = {
year: 2016,
month: 7,
day: 25,
hours: 22,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Create Date object as local
var date1 = new Date(
local.year,
local.month,
local.day,
local.hours,
local.minutes,
local.seconds,
local.milliseconds
);
// Create Date object as local from UTC
var date2 = new Date(Date.UTC(
utc.year,
utc.month,
utc.day,
utc.hours,
utc.minutes,
utc.seconds,
utc.milliseconds
));
var pre = document.getElementById('out');
// Display Date1 as local
pre.appendChild(document.createTextNode(date1.toString() + '\n'));
// Display Date2 as local
pre.appendChild(document.createTextNode(date2.toString() + '\n'));
// Display Date2 as UTC
pre.appendChild(document.createTextNode(date2.toUTCString() + '\n'));
// Test if Date1 and Date2 display the same datetime
pre.appendChild(document.createTextNode(
'Date1 === Date2: ' + (date1.getTime() === date2.getTime())
));
<pre id="out"></pre>
JSON converts Date objects to ISO 8601 (by specification), but let's see what happens if you use the solution that you chose.
// Values from the local datetime string
var local = {
year: 2016,
month: 7,
day: 26,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Create Date object as local
var date = new Date(
local.year,
local.month,
local.day,
local.hours,
local.minutes,
local.seconds,
local.milliseconds
);
// Your solution
var utcDate = new Date(Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes()));
var pre = document.getElementById('out');
// Display Date as local format
pre.appendChild(document.createTextNode(date.toString() + '\n'));
// Display utcDate as local format
pre.appendChild(document.createTextNode(utcDate.toString() + '\n'));
// Test if Date and utcDate display the same datetime
pre.appendChild(document.createTextNode(
'Date1 === Date2: ' + (date.getTime() === utcDate.getTime())
));
<pre id="out"></pre>
You end up with 2 dates that are no longer the same. Don't like ISO 8601 for transmission and storage of datetimes? Well the alternative would be to use the number of milliseconds UTC since the epoch (getTime). You can't make JSON do this conversion instead of ISO 8601, not even using a replacer function. So any conversion would be necessary before using JSON.stringify. So you really need to explain what it is you are trying to achieve and why you think what you have now is incorrect.
Use this
var result = Json.stringify(dt.toISOString());

Categories

Resources