我试图通过查找字符串并替换为当前日期来显示当前日期,但可以正常工作,但是我想显示另一个日期,如果字符串具有一些逗号分隔值,那么它将添加到当前日期并显示因此,可以说,如果我在字符串中添加(,30),它将在当前日期中增加30天并显示
var setCurrentDate = function() {
var disclaimerStr = $(".dynamic-date").html(),
currDateStr = "{currentdate}",
date = new Date(),
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
currDate =
months[date.getMonth()] +
" " +
date.getDate() +
", " +
date.getFullYear(),
newDisclaimerStr;
if (disclaimerStr.indexOf(currDateStr) != -1) {
newDisclaimerStr = disclaimerStr.replace(currDateStr, currDate);
$(".dynamic-date").html(newDisclaimerStr);
}
};
setCurrentDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-date">
<b>Current Date</b> : {currentdate} <br><br>
<b>Extended Date</b> : {currentdate,30} <br><br>
</div>
答案 0 :(得分:-1)
尝试此代码:
var setCurrentDate = function() {
var disclaimerStr = $(".dynamic-date").html(),
currDateStr = "{currentdate}",
date = new Date(),
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
currDate =
months[date.getMonth()] +
" " +
date.getDate() +
", " +
date.getFullYear(),
newDisclaimerStr;
if (disclaimerStr.indexOf(currDateStr) != -1) {
newDisclaimerStr = disclaimerStr.replace(currDateStr, currDate);
$(".dynamic-date").html(newDisclaimerStr);
}
var reg = new RegExp(/\{currentdate(,(\d+))\}/);
var currDateStr2 = '{currentdate,30}'; // you need to change here!
var days = parseInt(reg.exec(currDateStr2)[2], 10);
console.log(days) //30
var date2 = new Date();
date2.setDate(date2.getDate() + days);
console.log(date2) // "2019-04-27T09:13:00.789Z"
};
setCurrentDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-date">
<b>Current Date</b> : {currentdate} <br><br>
<b>Extended Date</b> : {currentdate,30} <br><br>
</div>