Obtain Duration of a quarter in Luxon - javascript

I'm trying to obtain the Duration (or start and end dates) of an arbitrary 'quarter' in Luxon.
For example, suppose I want the beginning and ending dates of the 3rd quarter knowing only the quarter:
const quarterInQuestion = 3;
const startDateOfQuarter = DateTime.fromFormat(quarterInQuestion.toString(), 'q');
This will give me the start date of the quarter, but how can I obtain the end date as well. I've looked into Durations and Intervals but can't seem to get anything to work yet.
Many thanks!

I think you want the endOf method, to which you can pass the period that you want the end of from a date.
const startDateOfQuarter = DateTime.fromFormat('3', 'q');
const endDateOfQuarter = startDateOfQuarter.endOf('quarter')

Related

Determine if a specific DateTime is within a time interval using Luxon

I'm trying to figure out how to check if a specific DateTime is within a time interval. For example, let's say I have a variable named dateTimeToCheck and I want to see if it is within the first quarter of the year (Jan 1st to March 31st).
I could use diff between dateTimeToCheck and Jan 1st and then diff between dateTimeToCheck and March 31st followed by some calculations, but I feel like there should be a cleaner way using Luxon's Interval or something like that.
Any help is very much appreciated!
Yes, you can use Luxon's Interval. The API has the contains method that:
Return whether this Interval contains the specified DateTime.
Here an example where I've used fromDateTimes to create Interval object:
const DateTime = luxon.DateTime;
const Interval = luxon.Interval;
const interval = Interval.fromDateTimes(DateTime.local(2023, 1, 1), DateTime.local(2023, 3, 31));
let dateTimeToCheck = DateTime.now();
console.log(interval.contains(dateTimeToCheck));
<script src="https://cdn.jsdelivr.net/npm/luxon#3.2.1/build/global/luxon.min.js"></script>

Javascript, trying to get date part time only

I have a date field coming from SQL as follows:
2022-06-30T00:00:00.000Z
Im trying to get the first 10 characters (date in format yyyy-mm-dd) from it, but I can't get it to work.
First, I tried a "left" function
textPaidThru= pt.slice(0,10)
And I got
Wed Jun 29
Then I tried moment
let textPaidThru = moment(paidThru).format('YYYY-MM-DD');
But Im getting this:
2022-06-29
No matter which method I try to use, I always get the provided date minus one day.
I encounter working with dates very hard in JS. Is there a way to get the date part only as provided by SQL? This is the value Im expecting:
2022-06-30
Thanks.
TL;DR; Timezones
Actual Answer
You could just use some vanilla javascript and parse it like this:
Note month is zero index in Date, so you will need to add 1 to each:
const dateToParse = "2022-06-30T00:00:00.000Z"
let parsedDate = new Date(dateToParse)
const formattedDate = `${parsedDate.getFullYear()}-${parsedDate.getMonth()+1}-${parsedDate.getDate()}`
console.log(formattedDate)
The reason you are getting 6-29 is most likely due to you not living in UTC+0. I get 6-29 as well, but that is because I live in UTC-7.
If you look in the code below I change the time to be UTC-7 (which should work for your timezone as well if what your profile says is correct UTC-3) and the console log for me displays 6-30 now.
const dateToParse = "2022-06-30T07:00:00.000Z"
let parsedDate = new Date(dateToParse)
const formattedDate = `${parsedDate.getFullYear()}-${parsedDate.getMonth()+1}-${parsedDate.getDate()}`
console.log(formattedDate)
If you know you'll always get the same format (well, you probably will), you can just use split, something like.
let dateTime = '2022-03-25T02:03:04.000Z';
let onlyDate = date.split('T')[0];
This will split the string at T and you basically only want the first part (array index 0) and that's it.

Moment, get financial start date based on end date

I have access to financial end date and need to compute the finanacial start date based on that.
This is the logic I have currently.
moment('2017-03-31', 'YYYY-MM-DD').quarter() would give me the quarter which in this case is 1.
I then subtract 3 months using
moment('2017-03-31', 'YYYY-MM-DD').subtract(3, 'months').format('YYYY-MM-DD') which results in 2016-12-31 and then I do all kinds of hacky computations to arrive at 2017-01-01.
Is there an elegant way to compute the start date using moment API's.
So essentially, given
2017-03-31 -> output: 2017-01-01
2017-12-31 -> output: 2017-10-01
let date = '2017-12-31'
moment(date).startOf('quarter').format('YYYY-MM-DD');
If it your goal to subtract 3 months from the end date and then result in a start date (which is the first of the month) maybe use:
moment().startOf('month');
Moment Docs
var d = moment('2017-03-31', 'YYYY-MM-DD').subtract(2, 'months').startOf('month').format('YYYY-MM-DD');
http://jsfiddle.net/rLjQx/57925/
you can use as per below :
var date = moment('2017-03-31').subtract(2, 'month').startOf('month').format('YYYY-MM-DD');
enter code here

MomentJS is comparing dates differently on the server

I want to group the events by day. In the development environment (Brazil) it does the group correctly, but on the server (USA) is not. Its's putting the events that take place at the end of the day at the beginning of the next day. I imagine that is related to the timezone.
The dates of the events are in the following format:
2016-11-03T18:00:00-0200
Below is my code, I tried a few things to solve this problem but could not. I'm using MomentJS to handle dates.The events must be grouped by the day regardless of the timezone, offset or anything else.
const events = [];
_.forEach(ungroupedEvents, event => {
const date = moment(event.start_time, moment.ISO_8601);
const period = _.find(events, period => date.isSame(period.date, 'day'));
if (period) {
period.events.push(event);
} else {
events.push({
date: date.format('L'),
events: [event]
});
}
});
How can I achieve this? I am all day and it does not get any progress. :(
You can try with moment-timezone and verify at each step that dates are formatted as UTC and input/output correctly for the right timezone (UTC/GMT).
Or, and I think this is best, use getTime() to get MS since epoch, store and group using that big number (you can use mod % to get day since epoch).

javascript date object changes

I have been reading up on dates for days, seemingly going in circles here. I have a string in a DB that looks like this
2012,03,13,01,31,38
I want to create a js date object from it so...
new Date(2012,03,13,01,31,38);
Easy enough, right? But it comes back as
2012-04-13 05:31:38 +0000
So the month is off by 1 and the time is off by 4 hours (maybe DST or Timezone related???). I simply want a date that matches the one I provided. Its driving me nuts, dealing with these JS date objects.
How can I be sure the date object is the exact same date and time as the string suggests, I have no need for Timezone or DST changes, simply a date that matches a string.
More specifics regarding application:
My application for this need is for an iphone app I am developing in Titanium (which builds using JS). Basically, part of my app involves logging data and with that log I collect the device's current date and time. I save all of this information to a mySQL database. The field in the database looks like this format: "2012-02-16 00:12:32"
Here is where I start to run into problems. I am now offering the ability to edit the log, including the date and time it was logged. In order to use an iPhone "picker", I must convert the string above into a JS date object again. This usually screws things up for me. I essentially need to create a new date object with the date above, with timezone and dst being completely irrelevant, so that when I save back to the DB, its just the string above, modified as per the users request. It needs to not matter whether they are editing in pennsylvania or china, they are editing the same log date.
Sorry if this has been confusing. I am having a hard time figuring out this whole date stuff.
This depends on what your string is. If that string is UTC time, you need to parse it as that. If it's local time, you need to parse it as local time. You can make a helper method like this for that part:
function getDate(utc, year, month, day, hour, minute, second) {
if(utc) {
var utc = Date.UTC(year, month - 1, day, hour, minute, second);
return new Date(utc);
} else {
return new Date(year, month - 1, day, hour, minute, second);
}
}
Now, to parse your string, you can use this:
function fromString(utc, str) {
var parts = str.split(',');
var year = parts[0];
var month = parts[1];
var day = parts[2];
var hour = parts[3];
var minute = parts[4];
var second = parts[5];
return getDate(utc, year, month, day, hour, minute, second);
}
which you can use like this for your example:
var d = fromString(true, '2012,02,13,00,31,38'); // If UTC
var d = fromString(false, '2012,02,13,00,31,38'); // If local time
Here's a working jsFiddle that you can play with:
http://jsfiddle.net/rNqXW/
which also shows two ways to print the date (UTC or local). Hope this helps.
I had the same problem. There are two reasons for the weird time change:
Use new Date(Date.UTC(2012,03,13,01,31,38)) to avoid the time change.
Note that the month is zero based! Months go from 0 to 11 for this function.

Categories

Resources