一、需求是这样,比如现在是2022-02-01,我要获取前两天的日期,结果应该是2022-01-30。
二、核心代码
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date day = sdf.parse("2017-01-01");
long ms = day.getTime() - 1*24*3600*1000L;
Date prevDay = new Date(ms);
System.out.println(sdf.format(prevDay));
}
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main{
public static void main(String[] args){
Date date = new Date();
String strDateFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println(sdf.format(date));
}
}
二、实例测试
1、测试java代码
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class Main {
public static void main( String[] args ) {
System.out.println( "Hello, World!" );
try{
function();
function_all("2022-02-03 03:08:06",1);
function_all("2022-02-03 12:10:17",2);
function_all("2022-02-03 16:13:28",3);
function_all("2022-02-03 23:53:59",4);
current_time();
function_all(current_time(),7);
} catch (ParseException e) {
e.printStackTrace();
}
System.exit( 0 ); //success
}
public static void function() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date day = sdf.parse("2017-01-01");
long ms = day.getTime() - 1*24*3600*1000L;
Date prevDay = new Date(ms);
System.out.println(sdf.format(prevDay));
}
public static void function_all(String str,int day_number) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date day = sdf.parse(str);
long ms = day.getTime() - day_number*24*3600*1000L;
Date prevDay = new Date(ms);
System.out.println(sdf.format(prevDay));
}
public static String current_time()
{
Date date = new Date();
String strDateFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println("current time:"+sdf.format(date));
return sdf.format(date);
}
}
2、运行结果,达到预计需求。
Hello, World! 2016-12-31 2022-02-02 03:08:06 2022-02-01 12:10:17 2022-01-31 16:13:28 2022-01-30 23:53:59 current time:2022-02-08 11:06:52 current time:2022-02-08 11:06:52 2022-02-01 11:06:52
三、某个项目中实际的应用
四、有价值的参考文章
java 获取前一天日期 - 偶尔发呆 - 博客园
Java 实例 – 格式化时间(SimpleDateFormat) | 菜鸟教程



