Date日期类:
Date中得出的数据都是long型的,所以需要日期与long类型的相互转换的方法:
- 将long转为Date: public Date(long date);
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
long cur = date.getTime();
cur += 864000 * 1000; // 十天的秒数
System.out.println(new Date(cur)); // long类型转换为Date
}
}
为什么要用long类型:因为long类型能够保存毫秒数据级,这样方便程序处理。
- 将Date转为long: public long getTime();
SimpleDateFormat日期格式化(来自java.text包):
继承抽象类DateFormat,然后DateFormat又继承Format,有如下方法:
-【继承DateFormat】将日期格式化: public final String format(Date date);
-【继承DateFormat】将字符串转为日期: public Date parse(String source) throws ParseException;
- 构造方法:public SimpleDateFormat(String pattern);
|- 日期格式:年(yyy)、月(MM)、日(dd)、时(HH)、分(mm)、秒(ss)、毫秒(SSS);
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
Thread.sleep(600);
Date date1 = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
String str = sdf.format(date1);
System.out.println(str);
}
}
}

字符串日期转换:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
// 字符串日期格式化
String bir = "2020-11-11 11:11:11.111"; // 字符串的日期
SimpleDateFormat asd = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
Date date = asd.parse(bir);
System.out.println(date);
}
}

在进行字符串的日期书写的时候,如果超过了合理的范围,将会自动进行进位处理。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)