1. 程式人生 > 實用技巧 >常用 js 操作日期類 自定義方法 原生 <input type="date" /> 日期格式化 日期設定 獲取指定天數後的日期

常用 js 操作日期類 自定義方法 原生 <input type="date" /> 日期格式化 日期設定 獲取指定天數後的日期

<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>

<body>

<form>
<input type="date" id="tempDate" name="tempDate"/>
</form>
<script th:src="@{/webjars/jquery/1.11.3/jquery.min.js}"></script>
</body>

<script>
$(function () {
//設定最小時間
$("#tempDate").attr("min",new Date().format("yyyy-MM-dd"))
     //設定預設值(包括顯示)
$("#tempDate").val(fun_date(new Date(),30))
});

/**
* 格式化日期
* @param fmt
* @returns {void|(function(*=): [*, *])|string|*}
*/
Date.prototype.format = function(fmt) {
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小時
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}

/**
* 獲取指定日期指定天數後的日期
* @param date
* @param chageDate
* @returns {string}
*/
function fun_date(date,chageDate){
var date2 = new Date(date);
date2.setDate(date.getDate()+chageDate);
var time2 = date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate();
return time2;
}
</script>
</html>