用于获取上周一的Java语言 [英] Javascript for getting the Previous Monday

查看:62
本文介绍了用于获取上周一的Java语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望上一个星期一出现在用户输入今天日期的字段中。

I would like for the previous Monday to appear in the field where a user enters today's date.

例如:如果输入了今天的日期 16.Jan-16 ,那么代码将改为显示上周一的日期(即 16-Jan-16 )。

E.g.: If today's date is entered 29-Jan-16 then the code would make the previous Monday's date to appear instead (which would be 25-Jan-16).

我在网上看到了一些代码:

I have seen some code online:

function getPreviousMonday()
{
    var date = new Date();
    if(date.getDay() != 0)
        return new Date().setDate(date.getDate()-7-6);
    else
        return new Date().setDate(date.getDate()-date.getDate()-6);
}

但是,这不太可行,为什么?

However, this is not quite working, why?

推荐答案

我认为您的数学知识还差一点,我整理了您的语法;

I think your maths is just a little off, and I tidied your syntax;

function getPreviousMonday()
{
    var date = new Date();
    var day = date.getDay();
    var prevMonday;
    if(date.getDay() == 0){
        prevMonday = new Date().setDate(date.getDate() - 7);
    }
    else{
        prevMonday = new Date().setDate(date.getDate() - day);
    }

    return prevMonday;
}

这样,您总是可以看到发生的最后一个星期一(7天前如果今天是星期一)

That way you always get the last monday that happened (which is 7 days ago if today is monday)

这篇关于用于获取上周一的Java语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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