How might I generate a list of date objects for each Monday of a year?
i want like
7 1 2019
14 1 2019
21 1 2019
...
4 3 2019
11 3 2019
blabla
Is there a function to do this in the DateTime library? i think i missed something,the same question asked for R but I really did not understand anything
As far as I know the function doesn't exist but you can try this code:
void main() {
var givenYear = 1999;
var listOfMondays = [];
var dateIter = DateTime(givenYear);
while (dateIter.year < givenYear + 1) {
dateIter.add(new Duration(days: 1));
if (dateIter.weekday == 1) {
//1 for Monday, 2 for Tuesday, 3 for Wednesday and so on.
listOfMondays.add(dateIter);
}
}
}
Related
hi I has date format and I want converted to correct GMT date :
<YYMMDDhhmmssNNN><C|D|G|H>
Sample value on that date:
210204215026000C
I get this explanation for part NNN :
NNN If flag is C or D then NNN is the number of hours relativeto GMT,
if flag is G or H, NNN is the number of quarter hours relative to GMT
C|D|G|H C and G = Ahead of GMT, D and H = Behind GMT
but I did not get how number of hours relative to GMT can present on 3 digits ? it should be in 2 digit as i knew the offset for hours related to GMT is from 0 to 23 , and also what quarter hours relative to GMT mean ?
I want to use Scala or Java.
I don’t know why they set 3 digits aside for the offset. I agree with you that 2 digits suffice for all cases. Maybe they just wanted to be very sure they would never run of out space, and maybe they even overdid this a bit. 3 digits is not a problem as long as the actual values are within the range that java.time.ZoneOffset can handle, +/-18 hours. In your example NNN is 000, so 0 hours from GMT, which certainly is OK and trivial to handle.
A quarter hour is a quarter of an hour. As Salman A mentioned in a comment, 22 quarter hours ahead of Greenwich means an offset of +05:30, currently used in Sri Lanka and India. If the producer of the string wants to use this option, they can give numbers up to 72 (still comfortably within 2 digits). 18 * 4 = 72, so 18 hours equals 72 quarter hours. To imagine a situation where 2 digits would be too little, think an offset of 25 hours. I wouldn’t think it realistic, on the other hand no one can guarantee that it will never happen.
Java solution: how to parse and convert to GMT time
I am using these constants:
private static final Pattern DATE_PATTERN
= Pattern.compile("(\\d{12})(\\d{3})(\\w)");
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuMMddHHmmss");
private static final int SECONDS_IN_A_QUARTER_HOUR
= Math.toIntExact(Duration.ofHours(1).dividedBy(4).getSeconds());
Parse and convert like this:
String sampleValue = "210204215026000C";
Matcher matcher = DATE_PATTERN.matcher(sampleValue);
if (matcher.matches()) {
LocalDateTime ldt = LocalDateTime.parse(matcher.group(1), FORMATTER);
int offsetAmount = Integer.parseInt(matcher.group(2));
char flag = matcher.group(3).charAt(0);
// offset amount denotes either hours or quarter hours
boolean quarterHours = flag == 'G' || flag == 'H';
boolean negative = flag == 'D' || flag == 'H';
if (negative) {
offsetAmount = -offsetAmount;
}
ZoneOffset offset = quarterHours
? ZoneOffset.ofTotalSeconds(offsetAmount * SECONDS_IN_A_QUARTER_HOUR)
: ZoneOffset.ofHours(offsetAmount);
OffsetDateTime dateTime = ldt.atOffset(offset);
OffsetDateTime gmtDateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("GMT time: " + gmtDateTime);
}
else {
System.out.println("Invalid value: " + sampleValue);
}
Output is:
GMT time: 2021-02-04T21:50:26Z
I think my code covers all valid cases. You will probably want to validate that the flag is indeed C, D, G or H, and also handle the potential DateTimeException and NumberFormatException from the parsing and creating the ZoneOffset (NumberFormatException should not happen).
As is shown below moment.diff() incorrectly calculates 0 days between yesterday (31 October) and today (1 November). Is this a problem with momentJS or with NodeJS (v14.15.4)?
> a = moment(new Date('2021-10-31'))
Moment<2021-10-31T02:00:00+02:00>
> b = moment(new Date('2021-11-01'))
Moment<2021-11-01T01:00:00+01:00>
> a.diff(b, 'days')
0
> a.diff(b, 'hours')
-24
One possible cause could be the summer => winter change that officially happened from Sun 31 Oct to Mon 1 Nov*. This is evident from the parsing of '2021-10-31' to a summer time Moment<2021-10-31T02:00:00+02:00> (2h).
Nevertheless, I would argue 24 hours diff should not come out as 0 days and thus it's a bug in Moment.
* Though everyone actually sets their clocks back on Sunday 31 Oct... go figure.
I think it's because there was the change of hour and that in .diff() for get the hour it's return a number lower than 1 and moment rounded it at 0.
You can change your code in that without use Date in the moment declaration:
const a = moment('2021-10-31');
const b = moment('2021-11-01');
console.log(a.diff(b, 'days')); // -1
console.log(a.diff(b, 'hours')); // -25 <- but this is wrong
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Or in alternative you can force that .diff() function returns a floating instead of integer putting the third parameter, and after round it like that:
const a = moment(new Date('2021-10-31'));
const b = moment(new Date('2021-11-01'));
console.log(Math.round(a.diff(b, 'days', true)));
console.log(Math.round(a.diff(b, 'hours', true)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Else is to force moment to use the utc date:
const a = moment.utc(new Date('2021-10-31'));
const b = moment.utc(new Date('2021-11-01'));
console.log(a.diff(b, 'days'));
console.log(a.diff(b, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I am trying to get week start as friday & end date as friday and I tried to use startOf/endOf week(week/isoweek) but failed. Is there any way that I can get friday as start of week and Friday as end of week using moment.
Moment(date).startOf('week'); // or isoweek
Output should be,
Date of friday
Request data:
First date= 05-09-2019
End date= 05-15-2019(current date)
Expected output:
[
{
Weekstart: 05-03-2019,
Weekend: 05-10-2019
},
{
Weekstart: 05-10-2019,
Weekend: 05-17-2019
}
]
There is no option for setting start day of week . But you can fetch last Friday date using
moment().weekday(-2).format("YYYY-DD-MM")
You can update the week start for a locale using something like:
moment.updateLocale(moment.locale(), { week: { dow: 5 } })
moment().startOf('week').toString(); // Fri May 10 2019 00:00:00 GMT+0100
You can do a short custom function to always give you start and end of the week based on a passed isoWeekDay:
let getCustomWeek = (dayOfWeek=7, date=new Date()) => {
let firstDay, lastDay, passedDay = moment(date).isoWeekday(dayOfWeek)
firstDay = moment(passedDay).subtract(1, 'week')
lastDay = moment(firstDay).add(1, 'week')
return { start: firstDay.format(), end: lastDay.format() }
}
let dateRange = ['05-09-2019', '05-15-2019']
console.log('Friday: ', dateRange.map(d => getCustomWeek(5, new Date(d))))
console.log('Wednesday: ', dateRange.map(d => getCustomWeek(3, new Date(d))))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Is there a way I could get a result like this:
Date1 is 1 minute 2 hours 3 days 4 years away from Date2
in Laravel 5 + Carbon between two dates?
It turned out Carbon::diffForHumans() method exists.
Some code for the curious:
$date1 = new Carbon();
$diff = $date1->diffForHumans($date2);
print 'Date1 is ' + $diff . ' away from Date2';
// output
// "Date1 is 3 weeks away from Date2"
OK so for example, today is Tuesday, Feb 02. Well the equivalent "Tuesday" from last year was on Feb 03.
How can I find this out programmatically?
Thanks!!
According to Google, there are 604,800,000 milliseconds in a week. That times 52 should give you the same day of the week a year later (right?).
For example:
var date:Date = new Date(2010, 1, 2);
trace(date);
date.setMilliseconds(date.milliseconds - 604800000 * 52);
trace(date);
Output:
Tue Feb 2 00:00:00 GMT-0800 2010
Tue Feb 3 00:00:00 GMT-0800 2009
Just my two cents. I don't like the idea, that the second answer assumes 52 weeks in a year, it will work for a single year, but is a solution to only this exact problem - eg. if you want to check the same thing moving back 10 years it won't work. I'd do it like this:
var today:Date = new Date();
// Here we store the day of the week
var currentDay:int = today.day;
trace (today);
const milisecondsInADay:uint = 1000*60*60*24;
// Here we move back a year, but we can just as well move back 10 years
// or 2 months
today.fullYear -= 1;
// Find the closest date that is the same day of the week as current day
today.time -= milisecondsInADay*(today.day-currentDay);
trace (today);
returns:
Tue Feb 2 21:13:18 GMT+0100 2010
Tue Feb 3 21:13:18 GMT+0100 2009