1.首先給出獲取當前時間的方法
function dateToString(){
var now=new Date(); var year = now.getFullYear(); var month =(now.getMonth() + 1).toString(); var day = (now.getDate()).toString(); var hour = (now.getHours()).toString(); var minute = (now.getMinutes()).toString(); var second = (now.getSeconds()).toString(); if (month.length == 1) { month = "0" + month; } if (day.length == 1) { day = "0" + day; } if (hour.length == 1) { hour = "0" + hour; } if (minute.length == 1) { minute = "0" + minute; } if (second.length == 1) { second = "0" + second; } var dateTime = year + "-" + month + "-" + day +" "+ hour +":"+minute+":"+second; return dateTime; }
返回當前時間字符串:dateTime = "2018-10-12 10:40:57"
獲取一定偏移量的時間
偏移量是毫秒ms,轉化成你要偏移的量的單位即可
以下假設以天為單位獲取30天之前的的時間
function dateToString(){
var now=new Date( new Date() - 1000 * 60 * 60 * 24 * 30);//最后一個30就是偏移量30天 var year = now.getFullYear(); var month =(now.getMonth() + 1).toString(); var day = (now.getDate()).toString(); var hour = (now.getHours()).toString(); var minute = (now.getMinutes()).toString(); var second = (now.getSeconds()).toString(); if (month.length == 1) { month = "0" + month; } if (day.length == 1) { day = "0" + day; } if (hour.length == 1) { hour = "0" + hour; } if (minute.length == 1) { minute = "0" + minute; } if (second.length == 1) { second = "0" + second; } var dateTime = year + "-" + month + "-" + day +" "+ hour +":"+minute+":"+second; return dateTime; }
結果:
new Date()
dateTime = "2018-10-12 10:40:57"
30天之前:
dateTime = "2018-09-12 10:40:57"
java獲取當前時間和偏移量
public static void main(String args[]){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date today = new Date(); String endDate = sdf.format(today);//當前日期 System.out.println(endDate); //獲取三十天前日期 Calendar theCa = Calendar.getInstance(); theCa.setTime(today); theCa.add(theCa.DATE, -30);//最后一個數字30可改,30天的意思 Date start = theCa.getTime(); String startDate = sdf.format(start);//三十天之前日期 System.out.println(startDate); }
輸出:
2018-10-12
2018-09-12
Process finished with exit code 0