萬年曆Calendar、js修改日期

//萬年曆
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-1); //改變日期,改變年份、月份相似
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("today is:" + format.format(Calendar.getInstance().getTime()));//格式化如今的時間
System.out.println("yesterday is:" + format.format(cal.getTime()));//格式化改變後的時間
System.out.println(cal.get(Calendar.YEAR));//得到年份
System.out.println(cal.get(Calendar.MONTH));//得到月份
System.out.println(cal.get(Calendar.DATE));//得到日期
System.out.println(cal.get(Calendar.HOUR));//得到小時
System.out.println(cal.get(Calendar.MINUTE));//得到分鐘
SimpleDateFormat format1 = new SimpleDateFormat("dd");               
System.out.println("today is:" + format1.format(Calendar.getInstance().getTime()));//格式化如今的時間,得到日期
System.out.println("yesterday is:" + format1.format(cal.getTime()));//格式化改變後的時間,得到日期
//JS
var date = new Date();
console.log(dateToStr(date));  //2015-12-21
date.setFullYear(date.getFullYear()-1);//年份減1年
date.setMonth(date.getMonth()-1);//月份減1月
date.setDate(date.getDate()-1);//日期減1天
date = new Date(date);
console.log(dateToStr(date));//2014-11-20

function dateToStr(date){  //date轉成字符串
    var str='';
    var month=date.getMonth()+1;
    str=date.getFullYear()+'-'+(month<=9?('0'+month):month)+'-'+(date.getDate()<=9?('0'+date.getDate()):date.getDate());
    return str;
}
var date = new Date(Date.parse($("#start").val().replace(/-/g, "/")))  //把input標籤選擇的時間轉成date
相關文章
相關標籤/搜索