当前位置 : 主页 > 编程语言 > java >

Java获取当前日期和一个月前日期

来源:互联网 收集:自由互联 发布时间:2022-07-13
SimpleDateFormat + Calendar import java . text . SimpleDateFormat ; import java . util . Calendar ; public class Test1 { public static void main ( String [] args ) { Calendar calendar = Calendar . getInstance (); SimpleDateFormat sdf = new


SimpleDateFormat + Calendar

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Test1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

// 获取当前日期
System.out.println(sdf.format(calendar.getTime()));

// 获取一个月前的日期
calendar.add(Calendar.MONTH, -1);
String endDate = sdf.format(calendar.getTime());
System.out.println(endDate);
}
}

Java8 LocalDateTime

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Test2 {
public static void main(String[] args) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now().minus(1, ChronoUnit.MONTHS);
System.out.println(localDateTime.format(dateTimeFormatter));
}
}

DateUtils

引入MVN库:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;

public class Test3 {
public static void main(String[] args) {
Date date = DateUtils.addDays(new Date(), -30);
System.out.println(date);
}
}


上一篇:Elasticsearch环境配置
下一篇:没有了
网友评论