根据当前时间获得本年结束时间,本月结束时间,本周结束时间,今日结束时间的13位时间戳并输出结果的java代码
时间: 2023-11-14 20:44:23 浏览: 84
java获取当前时间,一天开始结束时间,时间戳等
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeStampUtils {
/**
* 获取本年结束时间的13位时间戳
*
* @return 13位时间戳
*/
public static long getYearEndTimeStamp() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
* 获取本月结束时间的13位时间戳
*
* @return 13位时间戳
*/
public static long getMonthEndTimeStamp() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
* 获取本周结束时间的13位时间戳
*
* @return 13位时间戳
*/
public static long getWeekEndTimeStamp() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
calendar.add(Calendar.WEEK_OF_YEAR, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
* 获取今日结束时间的13位时间戳
*
* @return 13位时间戳
*/
public static long getTodayEndTimeStamp() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
* 根据字符串获取13位时间戳
*
* @param timeStr 时间字符串,格式为:yyyy-MM-dd HH:mm:ss
* @return 13位时间戳
* @throws ParseException 解析异常
*/
public static long getTimeStampByStr(String timeStr) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(timeStr);
return date.getTime();
}
public static void main(String[] args) throws ParseException {
System.out.println("本年结束时间的13位时间戳:" + getYearEndTimeStamp());
System.out.println("本月结束时间的13位时间戳:" + getMonthEndTimeStamp());
System.out.println("本周结束时间的13位时间戳:" + getWeekEndTimeStamp());
System.out.println("今日结束时间的13位时间戳:" + getTodayEndTimeStamp());
System.out.println("2021-12-31 23:59:59的13位时间戳:" + getTimeStampByStr("2021-12-31 23:59:59"));
}
}
阅读全文