Auto generate week number from selected date

92 views Asked by At

I have an XLSForm which I use to collect survey data. I have date, so when the user select the date, the year is autoclaved and displayed as "18, 0r 19" meaning 2018 or 2019 depending on the date selected. the month is also auto generated from the selected date. I want to Auto generate week number from selected date in an xlsForm to be used in ODK? e.g. when I select 5th 1-7th October, 2018. I want to automatically see this: Year is 18, Month is Oct, Week is Week1 of Oct.

1

There are 1 answers

0
vmf91 On

There will be two possible calculations. Take a look at the calendar.

calendar

Do you consider the third day as first week or second week?

If you consider it belongs to the first week, this function will solve your problem:

function getWeekNumberTypeA(dateStr, dateFormat) {
    var date = moment(dateStr, dateFormat);
    var day = date.date()
    return Math.ceil(day / 7)
}

But if you consider it belongs to the second week, then the following function will solve your problem:

function getWeekNumberTypeB(dateStr, dateFormat) {
    var date = moment(dateStr, dateFormat).toDate();
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);

    var dateBefore = moment(dateStr, dateFormat).toDate();
    dateBefore.setDate(1); // going to 1st of the month
    dateBefore.setHours(-1); // going to last hour before this date even started.

    var dateBeforeWeek = moment(dateBefore).week();
    var dateFirstDayWeek = moment(firstDay).week();
    var dateWeek = moment(date).week();

    if (dateFirstDayWeek == dateBeforeWeek) {
        return dateWeek - dateFirstDayWeek + 1
    } else {
        return dateWeek - dateFirstDayWeek
    }
}

Both functions receive a date string and a date format. Both functions also need moment js library.

Here you have some results:

getWeekNumberTypeA("02-04-2019", "MM-DD-YYYY")
result: 1

getWeekNumberTypeB("02-04-2019", "MM-DD-YYYY")
result: 2

getWeekNumberTypeA("02-28-2019", "MM-DD-YYYY")
result: 4

getWeekNumberTypeB("02-28-2019", "MM-DD-YYYY")
result: 5