在给定日期之前最接近的星期天使用JavaScript [英] the closest Sunday before given date with JavaScript

查看:76
本文介绍了在给定日期之前最接近的星期天使用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道 php & javascript

I need to know the date for last Sunday for given date in php & javascript

让我们有一个功能give_me_last_Sunday

Let's have a function give_me_last_Sunday

give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529

完全备份是在星期日=每周完成的。如果我要恢复每日备份,我需要全面(每周)和每日备份。我需要复制备份文件,然后恢复到临时目录,所以我恢复每日备份我需要知道每周备份文件,我需要沿日常文件复制。

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

我的想法是给给定日期的朱利安表示(或类似的东西),然后减去1并检查是否是星期天...不知道这是最好的想法,以及如何将给定日期转换为可以减去的东西。

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

推荐答案

根据托马斯的努力,提供的输入字符串完全是您指定的格式,然后:

Based on Thomas' effort, and provided the input string is exactly the format you specified, then:

function lastSunday(d) {
  var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
  d = new Date(d);
  d.setDate(d.getDate() - d.getDay());
  return d;
}



修改



如果我现在写这个,我不会依赖Date对象来解析字符串,而是自己做:

Edit

If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:

function lastSunday(s) {
  var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
  d.setDate(d.getDate() - d.getDay());
  return d;
}

虽然所有浏览器的yyyy / mm / dd格式正确解析,我认为坚持基本的方法是更健壮的。特别是当他们可能更有效率。

While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.

这篇关于在给定日期之前最接近的星期天使用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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