【发布时间】:2015-10-20 05:00:18
【问题描述】:
我正在尝试使用 jquery 以“mm-dd-yyyy”格式获取上周星期天的日期。有没有简单的解决方案?
【问题讨论】:
-
看看momentJs
我正在尝试使用 jquery 以“mm-dd-yyyy”格式获取上周星期天的日期。有没有简单的解决方案?
【问题讨论】:
用一句话得到最新的星期天:
var latestSunday = new Date(new Date().setDate(new Date().getDate() - new Date().getDay()));
用一句话搞定上周日:
var lastSunday = new Date(new Date().setDate(new Date().getDate() - (new Date().getDay()==0?7:new Date().getDay())));
似乎很冗长,你可以根据需要划分答案。然后,您可以使用其他日期格式插件来格式化日期,例如 jQuery dateFormat
【讨论】:
你可以解析字符串然后减去天的值得到上一个星期天
var string = '01-31-2015';
var date = new Date(string);
date.setDate(date.getDate() - date.getDay())
snippet.log(date)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
如果简单的日期解析不起作用,那么
var string = '01-31-2015';
var parts = string.split('-'),
date = new Date(parts[2], parts[0] - 1, parts[1]);
date.setDate(date.getDate() - date.getDay());
snippet.log(date)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
【讨论】:
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var firstday = new Date(curr.setDate(first)).toUTCString();
firstday
"Sun, 18 OCT 2015 12:25:40 GMT"
【讨论】: