获取当前时间戳System.currentTimeMillis()
老APIDate
在java.util中
Date date = new Date();
System.out.println(date.getYear() + 1900);
System.out.println(date.getMonth() + 1);
System.out.println(date.getDate());
自定义格式输出
import java.text.*;
import java.util.*;
public class main {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
}
Calendar
用于获取并设置年月日时分秒
import java.util.*;
public class Main {
public static void main(String[] args) {
// 获取当前时间:
Calendar c = Calendar.getInstance();
int y = c.get(Calendar.YEAR);
int m = 1 + c.get(Calendar.MONTH);
int d = c.get(Calendar.DAY_OF_MONTH);
int w = c.get(Calendar.DAY_OF_WEEK);
int hh = c.get(Calendar.HOUR_OF_DAY);
int mm = c.get(Calendar.MINUTE);
int ss = c.get(Calendar.SECOND);
int ms = c.get(Calendar.MILLISECOND);
System.out.println(y + "-" + m + "-" + d + " " + w + " " + hh + ":" + mm + ":" + ss + "." + ms);
}
}
从java8开始 java.time
提供了新的日期和时间API
本地日期和时间 LocalDate.now()
LocalTime.now()
LocalDateTime.now()
使用DateTimeFormatter
自定义输出格式
import java.time.*;
import java.time.format.*;
public class main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
System.out.println(dtf.format(LocalDateTime.now()));
//自定义格式解析
LocalDateTime dt2 = LocalDateTime.parse("2019/11/30 15:16:17",dtf);
System.out.println(dt2);
}
}
ZonedDateTime
用于表示带时区的日期和时间 Instant.now()
用于获取事件戳