计算从今天起过去的天数

时间:2022-08-25 19:00:03

Here is my issue:

这是我的问题:

I'm trying to calculate how many days passed from today's date and display it in a label.The issue is when the user changing the time,the result that I'm getting back is in fractions.

我试图计算从今天的日期过去多少天并将其显示在标签中。问题是当用户改变时间时,我得到的结果是分数。

Please assist

请协助

Here is my code in JS:

这是我在JS中的代码:

 //=============================================== //
   // How many days passed from the current day     //
   // ============================================ //

   function BanDateChanged(sender, args) {
       var banDate = $find("<%= rdtpBan.ClientID %>");
       var TodayDate = new Date();
       var today = new Date();
       var todayFormat = new Date(today.getMonth() + 1 + "/" + today.getDate() + "/" + today.getFullYear());
       var banSelectedDate = banDate.get_selectedDate();
       var countedBannedDays = document.getElementById("<%= lblBanCountDays.ClientID %>");
       var one_day = 1000 * 60 * 60 * 24;
       var countedDays = (Math.ceil(todayFormat - banSelectedDate) / one_day);
       if (countedDays == 0) {
           countedBannedDays.innerHTML = "";
       } else {
           countedBannedDays.innerHTML = countedDays + " Days ago";
       }
   }

3 个解决方案

#1


2  

Javascript dates are really just a timevalue that is milliseconds since 1970-01-01T00:00:00Z. To get the number of milliseconds between two dates, just subtract one from the other:

Javascript日期实际上只是一个时间值,自1970-01-01T00:00:00Z以来是毫秒。要获得两个日期之间的毫秒数,只需从另一个中减去一个:

var date0 = new Date(2015, 0, 1); // 1 Jan 2015
var date1 = new Date(2015, 1, 1); // 1 Feb 2015

var numberOfDays = Math.ceil((date1 - date0) / 8.64e7); // 31

Do not use the Date constructor to parse strings. If you know the values, pass them directly (remembering that months are zero indexed).

不要使用Date构造函数来解析字符串。如果您知道这些值,请直接传递它们(记住这些月份是零索引)。

To find out how many days have a passed since the beginning of the month, just use the day number:

要了解自月初开始已经过了多少天,只需使用日期编号:

var now = new Date();
var daysSinceStartOfMonth = now.getDate() - 1;

so on the 1st it will return 0, on the 2nd it will return 1 and so on. If you want to do it your way (which works but is a lot more work than it needs to be), then:

所以在1号它将返回0,在2号它将返回1,依此类推。如果你想按照自己的方式去做(有效但工作量远远超过它需要),那么:

// Create a date object for the current instant
var now = new Date();

// Make an exact copy
var startOfMonth = new Date(+now);

// Set the copy's date to the start of the month
startOfMonth.setDate(1);

// Get the difference in time value and calculate whole days
var daysSinceStartOfMonth = Math.ceil((now - startOfMonth) / 8.64e7); // 17 on 18 June

The only need for Math.ceil is if the dates cross a daylight saving boundary. Hope that helps.

Math.ceil的唯一需求是日期跨越夏令时边界。希望有所帮助。

#2


2  

You can get fractional results because of the mismatch in the time information so what you are looking for are "whole" days for a nice, round result. You can do that in a couple of ways. One is you can clear the time information from the dates being used by using the setHours() etc. functions. The second way would be to create a new Date object from banSelectedDate but without using its time information, like so:

由于时间信息不匹配,您可以获得小数结果,因此您所寻找的是“整天”,以获得良好的圆形结果。你可以通过几种方式做到这一点。一种是您可以使用setHours()等函数清除正在使用的日期的时间信息。第二种方法是从banSelectedDate创建一个新的Date对象,但不使用它的时间信息,如下所示:

var cDate = new Date(banSelectedDate.getFullYear(), banSelectedDate.getMonth(), banSelectedDate.getDate());

Then use cDate for the calculation.

然后使用cDate进行计算。

#3


0  

General case

This and many similar tasks were traditionally solved by reinventing the same solution over and over again, leading to problems during the development like you experienced here, and leaving a maintainability nightmare for the future.

这个和许多类似的任务传统上通过一遍又一遍地重新发明相同的解决方案来解决,导致在开发过程中出现问题,就像你在这里遇到的那样,并为未来留下可维护性的噩梦。

Fortunately there is a small library available for exactly cases like this: Moment.js.

幸运的是,有一个小型库可用于这样的案例:Moment.js。

Counting days

To display how many days have passed since a given date:

要显示自给定日期以来经过的天数:

var days = moment().diff("2015-06-02", "days");

It handles rounding for you, it handles daylight saving boundaries, it handles time zones, it handles date format parsing for you etc. - there is really no need to reinvent the wheel and write the same code many, many times. See: DEMO.

它为您处理舍入,它处理夏令时的边界,它处理时区,它为您处理日期格式解析等。 - 实际上没有必要重新发明*并多次编写相同的代码。见:DEMO。

But it gets even better than that:

但它比那更好:

More intelligent output

You can use this instead:

您可以使用此代替:

var ago = moment.duration(moment().diff("2015-06-05")).humanize() + " ago";

and you will automatically get values like:

并且您将自动获得如下值:

  • "15 days ago"
  • “15天前”
  • "13 hours ago"
  • “13小时前”
  • "5 years ago"
  • “5年前”

that would be ready to put in your countedBannedDays.innerHTML giving your users more informative values. See: DEMO.

这将准备好放入您的countBannedDays.innerHTML,为您的用户提供更多信息。见:DEMO。

Your example

In your example, as long as the value of your banSelectedDate contains a valid date, then your code - with the DOM handling code removed because that would stay the same:

在您的示例中,只要您的banSelectedDate的值包含有效日期,那么您的代码 - 删除DOM处理代码,因为它将保持不变:

    var banDate = $find("<%= rdtpBan.ClientID %>");
    var TodayDate = new Date();
    var today = new Date();
    var todayFormat = new Date(today.getMonth() + 1 + "/" + today.getDate() + "/" + today.getFullYear());
    var banSelectedDate = banDate.get_selectedDate();
    var one_day = 1000 * 60 * 60 * 24;
    var countedDays = (Math.ceil(todayFormat - banSelectedDate) / one_day);

can be simplified to just:

可以简化为:

    var banDate = $find("<%= rdtpBan.ClientID %>");
    var banSelectedDate = banDate.get_selectedDate();
    var countedDays = moment().diff(banSelectedDate, "days");

with the relevant days counting logic being just:

与相关的日计数逻辑只是:

var countedDays = moment().diff(banSelectedDate, "days");

var countsDays = moment()。diff(banSelectedDate,“days”);

It's obvious what's going on, you don't have to handle weird edge cases, you avoid exposing internal data representations leading to leaky abstractions, and there is really not much room to make any mistake.

很明显发生了什么,你不必处理奇怪的边缘情况,你避免暴露内部数据表示导致漏洞抽象,并且没有太多空间可以犯任何错误。

Other options

There are also other libraries:

还有其他图书馆:

See more info in this answer.

在这个答案中查看更多信息。

With good libraries available to handle such common tasks we don't have to write complicated code with many potential problems like the ones you had here. Code reuse not only allows you to avoid potential problems but it makes your own code much more maintainable.

有了可用于处理此类常见任务的良好库,我们无需编写具有许多潜在问题的复杂代码,例如您在此处遇到的问题。代码重用不仅可以避免潜在的问题,还可以使您自己的代码更易于维护。

#1


2  

Javascript dates are really just a timevalue that is milliseconds since 1970-01-01T00:00:00Z. To get the number of milliseconds between two dates, just subtract one from the other:

Javascript日期实际上只是一个时间值,自1970-01-01T00:00:00Z以来是毫秒。要获得两个日期之间的毫秒数,只需从另一个中减去一个:

var date0 = new Date(2015, 0, 1); // 1 Jan 2015
var date1 = new Date(2015, 1, 1); // 1 Feb 2015

var numberOfDays = Math.ceil((date1 - date0) / 8.64e7); // 31

Do not use the Date constructor to parse strings. If you know the values, pass them directly (remembering that months are zero indexed).

不要使用Date构造函数来解析字符串。如果您知道这些值,请直接传递它们(记住这些月份是零索引)。

To find out how many days have a passed since the beginning of the month, just use the day number:

要了解自月初开始已经过了多少天,只需使用日期编号:

var now = new Date();
var daysSinceStartOfMonth = now.getDate() - 1;

so on the 1st it will return 0, on the 2nd it will return 1 and so on. If you want to do it your way (which works but is a lot more work than it needs to be), then:

所以在1号它将返回0,在2号它将返回1,依此类推。如果你想按照自己的方式去做(有效但工作量远远超过它需要),那么:

// Create a date object for the current instant
var now = new Date();

// Make an exact copy
var startOfMonth = new Date(+now);

// Set the copy's date to the start of the month
startOfMonth.setDate(1);

// Get the difference in time value and calculate whole days
var daysSinceStartOfMonth = Math.ceil((now - startOfMonth) / 8.64e7); // 17 on 18 June

The only need for Math.ceil is if the dates cross a daylight saving boundary. Hope that helps.

Math.ceil的唯一需求是日期跨越夏令时边界。希望有所帮助。

#2


2  

You can get fractional results because of the mismatch in the time information so what you are looking for are "whole" days for a nice, round result. You can do that in a couple of ways. One is you can clear the time information from the dates being used by using the setHours() etc. functions. The second way would be to create a new Date object from banSelectedDate but without using its time information, like so:

由于时间信息不匹配,您可以获得小数结果,因此您所寻找的是“整天”,以获得良好的圆形结果。你可以通过几种方式做到这一点。一种是您可以使用setHours()等函数清除正在使用的日期的时间信息。第二种方法是从banSelectedDate创建一个新的Date对象,但不使用它的时间信息,如下所示:

var cDate = new Date(banSelectedDate.getFullYear(), banSelectedDate.getMonth(), banSelectedDate.getDate());

Then use cDate for the calculation.

然后使用cDate进行计算。

#3


0  

General case

This and many similar tasks were traditionally solved by reinventing the same solution over and over again, leading to problems during the development like you experienced here, and leaving a maintainability nightmare for the future.

这个和许多类似的任务传统上通过一遍又一遍地重新发明相同的解决方案来解决,导致在开发过程中出现问题,就像你在这里遇到的那样,并为未来留下可维护性的噩梦。

Fortunately there is a small library available for exactly cases like this: Moment.js.

幸运的是,有一个小型库可用于这样的案例:Moment.js。

Counting days

To display how many days have passed since a given date:

要显示自给定日期以来经过的天数:

var days = moment().diff("2015-06-02", "days");

It handles rounding for you, it handles daylight saving boundaries, it handles time zones, it handles date format parsing for you etc. - there is really no need to reinvent the wheel and write the same code many, many times. See: DEMO.

它为您处理舍入,它处理夏令时的边界,它处理时区,它为您处理日期格式解析等。 - 实际上没有必要重新发明*并多次编写相同的代码。见:DEMO。

But it gets even better than that:

但它比那更好:

More intelligent output

You can use this instead:

您可以使用此代替:

var ago = moment.duration(moment().diff("2015-06-05")).humanize() + " ago";

and you will automatically get values like:

并且您将自动获得如下值:

  • "15 days ago"
  • “15天前”
  • "13 hours ago"
  • “13小时前”
  • "5 years ago"
  • “5年前”

that would be ready to put in your countedBannedDays.innerHTML giving your users more informative values. See: DEMO.

这将准备好放入您的countBannedDays.innerHTML,为您的用户提供更多信息。见:DEMO。

Your example

In your example, as long as the value of your banSelectedDate contains a valid date, then your code - with the DOM handling code removed because that would stay the same:

在您的示例中,只要您的banSelectedDate的值包含有效日期,那么您的代码 - 删除DOM处理代码,因为它将保持不变:

    var banDate = $find("<%= rdtpBan.ClientID %>");
    var TodayDate = new Date();
    var today = new Date();
    var todayFormat = new Date(today.getMonth() + 1 + "/" + today.getDate() + "/" + today.getFullYear());
    var banSelectedDate = banDate.get_selectedDate();
    var one_day = 1000 * 60 * 60 * 24;
    var countedDays = (Math.ceil(todayFormat - banSelectedDate) / one_day);

can be simplified to just:

可以简化为:

    var banDate = $find("<%= rdtpBan.ClientID %>");
    var banSelectedDate = banDate.get_selectedDate();
    var countedDays = moment().diff(banSelectedDate, "days");

with the relevant days counting logic being just:

与相关的日计数逻辑只是:

var countedDays = moment().diff(banSelectedDate, "days");

var countsDays = moment()。diff(banSelectedDate,“days”);

It's obvious what's going on, you don't have to handle weird edge cases, you avoid exposing internal data representations leading to leaky abstractions, and there is really not much room to make any mistake.

很明显发生了什么,你不必处理奇怪的边缘情况,你避免暴露内部数据表示导致漏洞抽象,并且没有太多空间可以犯任何错误。

Other options

There are also other libraries:

还有其他图书馆:

See more info in this answer.

在这个答案中查看更多信息。

With good libraries available to handle such common tasks we don't have to write complicated code with many potential problems like the ones you had here. Code reuse not only allows you to avoid potential problems but it makes your own code much more maintainable.

有了可用于处理此类常见任务的良好库,我们无需编写具有许多潜在问题的复杂代码,例如您在此处遇到的问题。代码重用不仅可以避免潜在的问题,还可以使您自己的代码更易于维护。