在PHP中像JavaScript一样在一年中获得一周 [英] Get week of year in JavaScript like in PHP

查看:123
本文介绍了在PHP中像JavaScript一样在一年中获得一周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得当年的当前周数,如PHP的日期('W')

How do I get the current weeknumber of the year, like PHP's date('W')?

应该是 ISO-8601 周年数,周数

It should be the ISO-8601 week number of year, weeks starting on Monday.

推荐答案

你应该可以在这里获得你想要的: http://www.merlyn.demon.co.uk/js-date6.htm#YWD

You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD.

同一网站上的更好的链接是: 使用周数

A better link on the same site is: Working with weeks.

这里是一些基于提供的链接的代码,多米诺根据 http:/ /www.merlyn.demon.co.uk/js-date6.htm#YWD 。请仔细检查,不保证。

Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD. Please test thoroughly, no guarantee provided.

/* For a given date, get the ISO week number
 *
 * Based on information at:
 *
 *    http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
 *
 * Algorithm is to find nearest thursday, it's year
 * is the year of the week number. Then get weeks
 * between that date and the first day of that year.
 *
 * Note that dates in one year can be weeks of previous
 * or next year, overlap is up to 3 days.
 *
 * e.g. 2014/12/29 is Monday in week  1 of 2015
 *      2012/1/1   is Sunday in week 52 of 2011
 */
function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(+d);
    d.setHours(0,0,0,0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay()||7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(),0,1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
    // Return array of year and week number
    return [d.getFullYear(), weekNo];
}

var result = getWeekNumber(new Date());
document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);

小时需要归零,以防日期对象迟到。

Note that hours need to be zeroed in case a date object is passed with a late time.

最小化原型版本(仅返回周号):

Minimized, prototype version (returns only week-number):

Date.prototype.getWeekNumber = function(){
    var d = new Date(+this);
    d.setHours(0,0,0,0);
    d.setDate(d.getDate()+4-(d.getDay()||7));
    return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
};

document.write('The current ISO week number is ' + new Date().getWeekNumber());

这篇关于在PHP中像JavaScript一样在一年中获得一周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆