javascript - 每年倒数一天(并找到当年那一天的日期)

标签 javascript jquery datetime momentjs countdowntimer

我想做一些非常复杂的事情,我一直在使用 moment.js 或 countdown.js 来尝试解决这个问题,但我认为我的要求太复杂了?我可能是错的。这是标准...

我需要能够实现以下目标,而无需每年手动更改日期,只需添加一次并且在一页上有多个倒计时。

  1. Find current date
  2. Find current year
  3. Find current month
  4. Find day within week of month that applies ¬ 3rd Sunday or 2nd Saturday
  5. Convert to JS and output as html and run countdown
  6. When past date - reset for following year

很精神。因此,例如,如果一个事件总是在三月的第三个星期日。每年的日期都不一样。

  1. 2016 - Sunday March 19th
  2. 2017 - Sunday March 20th
  3. 2018 - Sunday March 18th etc.

我希望这得到很好的解释,但我意识到这可能是一团糟。我设法让它每年重置并手动添加日期,但后来有人把 Spanner 扔进了date 每年都不同的地方。

var event = new Date();
event = new Date(event.getFullYear() + 1, 3 - 1, 19);
jQuery('#dateEvent').countdown({ until: event });


<div id="dateEvent"></div>

最佳答案

我已经编辑了这个答案,因为我现在已经整合了一个适合我的解决方案。我相信这不是简单的编码,因为它实际上并没有回答'拜托,这是基本编码。拿起一本 javascript 书并学习编码',是的,谢谢......

// get the specific day of the week in the month in the year
        function getDay(month) {
            // Convert date to moment (month 0-11)
            var myMonth = moment("April", "MMMM");
            // Get first Sunday of the first week of the month
            var getDay = myMonth.weekday(0); // sunday is 0
            var nWeeks = 3; // 0 is 1st week
            // Check if first Sunday is in the given month
            if (getDay.month() != month) {
                nWeeks++;
            }
            // Return 3rd Sunday of the month formatted (custom format)
            return getDay.add(nWeeks, 'weeks').format("Y-MM-D h:mm:ss");
        }

        // print out the date as HTML and wrap in span
        document.getElementById("day").innerHTML = '<span>' + getDay() + '</span>';

使用

<script src="moment.js"></script>

希望它对某人有所帮助 - 当我想出如何在检查当前日期和事件过去 1 年后进行更新时,我会进行更新。我会看看那本 JS 书。

关于javascript - 每年倒数一天(并找到当年那一天的日期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46073220/

相关文章:

javascript - ui-bootstrap(Angular.JS)中选项卡的淡入淡出效果

javascript - Cordova 中的确认对话框

javascript - 将 JS 变量输出到我的 PHP 文件中

datetime - 尝试从 Racket 中的字符串创建日期 - 查找秒非常慢,需要工作日年日?

javascript - 将二进制字符串转换为其补码

javascript - 嵌入式与链接的 JS/CSS

javascript - 添加 account-ui 包后,Meteor 模板被创建两次

javascript - 动态加载的 div 内容中的 jQuery 工具提示

c# - 从 Windows 文件时间转换为 DateTime

java - 日历无法正确设置小时