[英]Convert string as 'mm/dd/yyyy' to 'day of week, month name, year' in javascript
[英]JavaScript: Convert Day/Week Into Year
因此,假设您分别具有3
和43
的值,您可以在当年的第一天做一些简单的数学运算:
这样的事情可能是:
var currentDate = new Date();
var startOfYear = new Date(currentDate.getFullYear(), 0, 1);//note: months start at 0
var daysToAdd = (43 * 7) + 3;
//add days
startOfYear.setDate(startOfYear.getDate() + daysToAdd);
编辑
再想一想,我认为我的要求是错的。 您似乎需要一周中的特定日期。 检查一下以获得更好的解决方案。
问题是这一切都取决于你对一周的定义。 今年是星期天开始的,这是否意味着02/01/2012(今年的第一个星期一)是第二周的开始?
我的最新示例将首先找到指定周的开始,然后查找指定日期的下一个出现
这个解决方案确实需要添加额外的库,但我认为它确实值得。 它是一个用于操纵日期和时间的momentjs库。 它得到积极维护,并有很好的文档 。 获得day和weekNumber的值(在我们的案例3和43中),您应该执行以下操作:
function formatInput(day, weekNumber){
var currentDate = moment(new Date()); // initialize moment to a current date
currentDate.startOf('year'); // set to Jan 1 12:00:00.000 pm this year
currentDate.add('w',weekNumber - 1); // add number of weeks to the beginning of the year (-1 because we are now at the 1st week)
currentDate.day(day); // set the day to the specified day, Monday being 1, Sunday 7
alert(currentDate.format("dddd, MMMM Do YYYY")); // return the formatted date string
return currentDate.format("dddd, MMMM Do YYYY");
}
我认为这个库以后可能对你有用,并且有很多关于日期和时间操作的可能性,以及格式化选项。 还有一个伟大的文档为momentjs写。
根据ISO处理周日期时,周从星期一开始,一年的第一周是包含一年中第一个星期四的那一周。 因此,对于2012年,第一周于1月2日星期一开始,2013年第一周将于2012年12月31日星期一开始。
因此,如果3/43是第43周的第三天(即ISO日期2012-W43-3),则可以使用以下方法将其转换为日期对象:
function customWeekDateToDate(s) {
var d, n;
var bits = s.split('/');
// Calculate Monday of first week of year this year
d = new Date();
d = new Date(d.getFullYear(),0,1); // 1 jan this year
n = d.getDay();
d.setDate(d.getDate() + (-1 * n +( n<5? 1 : 8)));
// Add days
d.setDate(d.getDate() + --bits[0] + --bits[1] * 7);
return d;
}
console.log(customWeekDateToDate('3/43')); // 01 2012-10-24
请注意,这会使用日期,否则夏令时转换可能会导致错误的日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.