本文介绍了我如何比较今天的日期与发布日期和默认为今天的日期如果发布日期是过去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 问候, 我需要在JavaScript中验证获取今天日期的日期字段,将今天的日期与发布日期进行比较,如果发布日期是比今天的日期早,将字段值默认为今天的日期。我在下面列出了我的示例代码...Greetings,I need to validate a date field in JavaScript that acquires today's date, compares today's date to the posted date, and, if the posted date is older than today's date, default the field value to today's date. I have listed my sample code below...function isValidDate(dateString){ var todaysdate = (Date.now()); // First check for the pattern var regex_date = /^\d{1,2}\-\d{1,2}\-\d{4}$/; if (!regex_date.test(dateString)) { return false; } // Parse the date parts to integers var parts = dateString.split("-"); var day = parseInt(parts[2], 10); var month = parseInt(parts[1], 10); var year = parseInt(parts[0], 10); // Check the ranges of month and year if (year < 1000 || year > 3000 || month == 0 || month > 12) { return false; } var posteddate = new Date(dateString); if (todaysdate > posteddate) { return false; } var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Adjust for leap years if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) { monthLength[1] = 29; } // Check the range of the day return day > 0 && day <= monthLength[month - 1];}推荐答案 这篇关于我如何比较今天的日期与发布日期和默认为今天的日期如果发布日期是过去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-11 02:13