How to use intervalToDuration function from date-fns - javascript

I tried using the intervalToDuration function from date-fns but I keep getting an error that says End Date is invalid.
My code is as follows
import { intervalToDuration} from "date-fns";
remaining() {
const now = new Date();
const end = this.endDate;
return intervalToDuration({
start: now,
end: end,
});
},
this.endDate is dynamically populated but for this question is equal to 2021-02-26T00:00:00.000Z

Since your endDate variable is coming from an API, it is being stored as a string, not a date.
Calling intervalToDuration is expecting an interval object to be passed as the parameter. An interval consists of two Dates or Numbers (unix timestamp)
To correct this, you must convert endDate to a date object, below is an untested example;
const remaining = () => {
const endDate = "2021-02-26T00:00:00.000Z";
const now = new Date();
const end = new Date(endDate);
return intervalToDuration({
start: now,
end: end
});
};
const dur = remaining();
console.log("DURRATON ", JSON.stringify(dur));
//
// Response == DURRATON {"years":0,"months":1,"days":8,"hours":15,"minutes":42,"seconds":0}
//
Notice : This does not handle timezones correctly. new Date() will create a datetime in the client timezone where it appears that your response from the API is in GMT timezone

Related

Moment Timezone not returning expected result

I might be doing something silly here. But essentially, the time in Lisbon right now is 12:27 PM
but the following returns 14:27 (EU central time)
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment.tz(item.startTime, format, timeZone);
const endMoment = moment(item.endTime, format, timeZone);
return time.isBetween(startMoment, endMoment);
I tried several combinations and I get the wrong answer everytime. For example if I set timeZone to be "Europe/Warsaw" it returns 15:27 whereas it should be 13:27.
EDIT: const currentTime = moment().tz("Europe/London").format() returns the correct time for London. However, the return statement moment(currentTime).isBetween(startMoment, endMoment) still reads "moment(correntTime)" as the local time.
isBetween return boolean . And isBetween runs on date object. You are trying to run on time zone object. which is different from date object
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment().subtract(8, 'months').tz(timeZone).format();
const endMoment = moment(new Date()).tz(timeZone).format() ;
console.log("startMoment",startMoment)
console.log("endMoment",endMoment)
console.log(moment.tz(new Date(),"Europe/Lisbon").format())
console.log(moment('2020-09-30').isBetween(startMoment, endMoment));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

Removing offset from a javascript Date

I'm trying to remove the javascript Date offset, so that the local time a date was recorded in from a given country can be displayed.
I have a test that only works when the timezone is GMT
describe('.removeLocalDateOffset()', () => {
it('removes the timezone offset', () => {
const input = '2017-10-03T08:53:12.000-07:00';
const result = removeLocalDateOffset(input);
expect(result.toISOString()).toBe('2017-10-03T08:53:12.000Z');
});
});
And the function I want to do the job:
const removeLocalDateOffset = (date) => {
const originalDate = new Date(date);
return new Date(Date.UTC(
originalDate.getFullYear(),
originalDate.getMonth(),
originalDate.getDate(),
originalDate.getHours(),
originalDate.getMinutes(),
originalDate.getSeconds(),
));
}
Any suggestions for how I can do this using the methods of the new Date() object? Ideally not doing a .slice() on a substring.
Test Results. I am currently in GMT:
Expected: "2017-10-03T08:53:12.000Z"
Received: "2017-10-03T16:53:12.000Z"

How to compare Current System date with with another date

I am getting date in string format from API.
End Date 2014-06-03T06:16:52. I need to write an if-else logic and compare the end date and current date.If end date is less than current date then show customer as In Active and if end date is greater than display the Customer as Active.
I have tried following logic but I am not able to understand and get today's time in string fromat.
this.endDate = this.sampleData != null ?
this.sampleData.customerStartDate : null;
this.currentDate = new Date();
var dd = this.currentDate.getDate();
var mm = this.currentDate.getMonth() + 1;
var yyyy = this.currentDate.getFullYear();
this.currentDate = new Date().toLocaleString()
console.log('End Date', this.endDate);
console.log('Current Date: ', this.currentDate);
if (this.endDate == null) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'In Active';
}
I am getting current date as Current Date: 4/2/2019, 1:23:34 AM
I want to be able to get in same format as End Date.
My main task is to compare the dates how do I achieve it ?
Ideally you want to clean up the date you're getting from an API, and convert it to a JS Date object. You can do this by keeping only the 2014-06-03T06:16:52 part, and giving it to the new Date() constructor.
You can get the current date by calling new Date() without parameters.
You can the turn the dates in to numbers by calling getTime() on each.
You can then compare the numbers.
const incoming_date = new Date('2014-06-03T06:16:52');
const current_date = new Date();
if (incoming_date.getTime() < current_date.getTime() {
// incoming_date is before current_date
} else {
// current_date is before incoming_date
}
as simple as this:
let date=new Date("2014-06-03T06:16:52")
date>new Date()
you could try to express dates in ms since the Unix Epoch with getTime() and compare them
if (currDate.getTime() > endDate.getTime()) {
// set customer to inactive
} else {
// keep customer active
}
I personally like to use moment() for javascript dates. You really just need to have it compare the same format, so you could have something like:
this.currentDate = moment().toISOString();
const dataDate = this.sampleData ? this.sampleData.customerStartDate : null;
this.endDate = moment(dataDate).toISOString();
if (this.endDate > this.currentDate) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'Inactive';
}

get an array of dates from today for datepicker with Javascript

I am trying to write a function that returns an array of dates from today till the maximum date, so that I can restrict the date picker selection. At the moment I have the following:-
datesAfterToday: function (date) {
var dates = []
var currentDate = new Date()
var endDate = new Date(8640000000000000).getFullYear()
var addDays = function (days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() + days)
return date
}
while (currentDate <= endDate) {
dates.push(currentDate)
currentDate = addDays.call(currentDate, 1)
}
return dates
}
and then I am using Vue.js to mount it as follows :-
mounted () {
this.allowedDates = this.datesAfterToday
},
however I am only getting an array of objects instead of the proper array.
How can I get the proper array of dates so that I can bind it to the allowdates property.
Thanks for your help and time!
For starters new Date(8640000000000000).getFullYear() will set endDate to the year of that date, which is 275760. currentDate will be today's date (in milliseconds), which at the time of me writing is 1511272934156. As you can see currentDate is always greater than endDate, so your while loop never goes to the statements inside.
Another issue is that the date you picked is really far in the future and you're populating an array one day at a time. Your loop will most likely make the page freeze or crash completely. Try picking a date that's more manageable.
For instance, in the snippet below I set endDate by first initializing it to today, then setting the year to exactly one year from now. This gives me an array with roughly 365 values.
You can imagine how big this array would be if I used a year that was 273,748 years in the future.
var dates = []
var currentDate = new Date()
var endDate = new Date()
endDate.setFullYear(endDate.getFullYear()+1)
var addDays = function (days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() + days)
return date
}
while (currentDate <= endDate) {
dates.push(currentDate)
currentDate = addDays.call(currentDate, 1)
}
console.log(dates)
With all that being said, it looks like you're actually allowed to pass an object specifying the minimum and maximum values rather than an array.
https://vuetifyjs.com/components/pickers#example-6
let d = new Date() // today
let d2 = new Date()
d2.setFullYear(date.getFullYear()+1) // Next year
this.allowedDays = {
min : d.toISOString().substr(0, 10), // e.g. 2017-11-21
max : d2.toISOString().substr(0, 10)
}
Another option would be to use vuejs-datepicker For example:
<script>
var state = {
disabled: {
to: new Date(), // Disable all dates up to specific date
from: new Date(8640000000000000) // Disable all dates after specific date
}
}
</script>
<datepicker :disabled="state.disabled"></datepicker>
See Disabled Dates in the documentation.

How to convert string to ISOString?

I have 3 variables: (1)Date (2) StartTime (3) EndTime
I would like to bring them as two variables (1)Date and StartTime (2) Date and EndTime, so that I can create a google calendar event.
As per my understanding, in order to create a google calendar event I need to pass ISO String format for event timings. Can anyone check the below code and help me with the missing piece.
function createEvent(title,Dt,startTime,endTime,col) {
var calendarId = '_____#group.calendar.google.com';
Logger.log(Dt); //2016-07-21
Logger.log(startTime); // 11:55 AM
Logger.log(typeof(startTime)); //string
//Help Needed to convert + to ISO
var event = {
summary: title,
start: {
dateTime: startISO
},
end: {
dateTime: endISO
},
colorId: col
};
event = Calendar.Events.insert(event, calendarId);
Logger.log('Event ID: ' + event.getId());
You can use .toISOString() on the Date object to get an ISO String, but Google Calendar is requesting a slightly different format than this, but it is a quick fix. Start with a normal conversion:
(new Date()).toISOString(); // "2016-07-29T00:00:00.000Z"
var startTime = new Date();
var isoStartTime = startTime.toISOString();
If you need to make the Date from separate objects you can:
var yourDate = '2016-07-29';
var yourTime = '11:55 AM';
var startTime = new Date(yourDate);
startTime.setHours(yourTime.split(':')[0]); // 11
startTime.setMinutes(yourTime.split(':')[1].substr(0,2)); // 55
startTime = startTime.toISOString(); // "2016-07-29T11:55:00.000Z"
Then change it to what Google's looking for:
// To RFC 3339...
startTime.substr(0,startTime.length-5)+'Z'; // "2016-07-29T11:55:00Z"
Or
//if the "startTime = startTime.toISOString()" assignment happened
startTime.split('.')[0]+'Z';
//if startTime is a Date object, not a string
startTime.toISOString().split('.')[0]+'Z';
You can also (and probably preferrably) use numbers instead of strings for all that; if you pass hours and minutes separately it could look cleaner than that string operation:
var startTime = new Date(yourDate);
startTime.setHours(yourHours); // string or int
startTime.setMinutes(yourMinutes); // string or int

Categories