问题
In Google Script I have the following code:
var myDate = new Date(sheet.getRange(3,1).getValue());
var year = Utilities.formatDate(myDate, "Europe/Amsterdam", 'dd-MM-yyyy');
var weekyear = Utilities.formatDate(myDate, "Europe/Amsterdam", 'dd-MM-YYYY');
var week = Utilities.formatDate(myDate, "Europe/Amsterdam", 'w');
When I insert 30-12-2015 as date, the result will be.
// year: 30-12-2015
// weekyear: 30-12-201**6**
// week: 1
In my local timezone, it should be week number 53. Not 1. If I calculate the week in ISO 8601, the result is 52.
Strange, isn't it?
Edited: New attempt, with this code
var cursus_datum = sheet.getRange(3,1).getValue();
Logger.log('type of data: ' + typeof cursus_datum);
Logger.log(cursus_datum);
Logger.log(Utilities.formatDate(cursus_datum, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "d-MM-y HH:mm"));
Logger.log(Utilities.formatDate(cursus_datum, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "w"));
This results in
// type of data: object
// Wed Dec 30 09:00:00 GMT+01:00 2015
// 30-12-2015 00:00 which is perfect
// 1 which is **not** correct.
The wrong week is the bug.
回答1:
The Utilities.formatDate documentation states that it uses Java SimpleDateFormat - I have a feeling this might be the cause of the problem as they are Locale sensitive and I would take a guess it will be using the default US locale (I don't think passing in the timezone changes the locale). The problem is the US locale calendar has getFirstDayOfWeek() = 1 (SUNDAY) and getMinimalDaysInFirstWeek() = 1. And for ISO 8601 you need the settings 2 and 4 respectively. I think you're better off sticking to the Javascript code you linked to if you want to work with week years.
回答2:
new Date() will accept a few different parameter configurations, but you still need to make sure that the parameters are correct. You can't just plug anything into new Date() If the variable is already a date type, then there is no point using new Date(). You can test for the data type with typeof.
var dateFromSheet = sheet.getRange(3,1).getValue();
Logger.log('type of data: ' + typeof dateFromSheet);
If the data type is a string, it must be in a valid date string format. There are a few different formats. But, again, you need to use a valid format.
- ISO 8601 syntax "YYYY-MM-DD" or "YYYY-MM" or "YYYY" or "YYYY-MM-DDTHH:MM:SS"
- Long Date syntax - Year, month and day can be in any order: "Mar 7 2015" or "2015 Mar 7", and Month can be written in full: "2015 March 7"
- Short dates - "/" or "-" can be used. "MM/DD/YYYY" or "YYYY/MM/DD" NOTE: You can not use "DD/MM/YYYY"
- Full Date Format - "Wed Mar DD YYYY HH:MM:SS GMT+0100 (W. Europe Standard Time)"
来源:https://stackoverflow.com/questions/34204388/utilities-formatdate-returning-wrong-week-number