思路:计算两日期间有多少天,递归调用Calendar获取昨天
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @version:
* @Description:
* @author: hxk
* @date: 2020/8/5
*/
public class UTCparse {
public static void main(String[] args) throws Exception {
System.out.println(formatUTC("2020-08-05 07:59:30"));
System.out.println(yesterday(new SimpleDateFormat("yyyy-MM-dd").parse("2019-01-02").getTime()));
System.out.println(betweendays(null,null));
long num = betweendays(null,null);
yesterday(new SimpleDateFormat("yyyy-MM-dd").parse("2018-11-10").getTime(),num);
}
public static String yesterday(long date){
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
// 设置指定日期,月份需要减一
calendar.setTime(new Date(date));
calendar.set(Calendar.HOUR_OF_DAY,-24);
String yesterdayDate=dateFormat.format(calendar.getTime());
return yesterdayDate;
}
public static String yesterday(long date,long times){
DateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
// 设置指定日期,月份需要减一
calendar.setTime(new Date(date));
calendar.set(Calendar.HOUR_OF_DAY,-24);
String yesterdayDate=dateFormat.format(calendar.getTime());
System.out.println(yesterdayDate);
if(times>0){
times = times - 1;
yesterday(calendar.getTimeInMillis(),times);
}
return yesterdayDate;
}
public static long betweendays(String start,String end) throws Exception {
//设置转换的日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//开始时间
Date startDate = sdf.parse("2018-10-29");
//结束时间
Date endDate = sdf.parse("2018-11-10");
//得到相差的天数 betweenDate
long betweenDate = (endDate.getTime() - startDate.getTime())/(60*60*24*1000);
//打印控制台相差的天数
System.out.println(betweenDate);
return betweenDate;
}
public static String formatUTC(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat utcSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar cal = Calendar.getInstance();
// 取得时间偏移量:
int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
// 取得夏令时差:
int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
try {
Date dateValue = sdf.parse(date);
long longDate = dateValue.getTime();
longDate = longDate - zoneOffset - dstOffset;
Date UTCDate = new Date(longDate);
return utcSdf.format(UTCDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
2020-08-04T23:59:30.000Z
2019-01-01
12
12
12
20181109
20181108
20181107
20181106
20181105
20181104
20181103
20181102
20181101
20181031
20181030
20181029
20181028