我们需要使用到Date 与 SimpleDateFormat以及System
第一种方法:
使用Date与SimpleDateFormat
class Test{
public static void main(String[] args){
Date d1=new Date();
SimpleDateFormat as=new SimpleDateFormat();
String asd=as.format(d1);
System.out.println(asd);
}
}
首先通过Date 得到d1 ,代表一个日期,但是这个日期并不便于阅读,’
所以我们在使用SimpleDateFormat 以及它的format方法,
得到一种特定格式的日期的字符串 asd
得到结果: 2022/4/24 下午4:16,数以 “2022/4/24 下午4:16”是一个字符串,
第二种方法:增加了System的使用
不同的是:
开头我们使用了System.currentTimeMillis()方法;
得到了一个当前时间的时间毫秒值
然后我们就要将时间毫秒值转化为Date 的日期格式
使用System.currentTimeMillis()的优点是便于对时间经行修改;
因为Date要修改时间也要转化为时间毫秒值
代码如下:
class Test{
public static void main(String[] args){
long toDayTime=System.currentTimeMillis();
Date tDT=new Date(toDayTime);
SimpleDateFormat date=new SimpleDateFormat();
String dateTime=date.format(tDT);
System.out.println(dateTime);
}
}
本文介绍了两种在Java中处理日期的方法。第一种是直接使用Date和SimpleDateFormat将日期转换为易读的字符串。第二种方法结合了System.currentTimeMillis(),先获取当前时间的毫秒值,再转化为Date对象,最后同样用SimpleDateFormat格式化输出。这种方式便于对时间进行修改。
360

被折叠的 条评论
为什么被折叠?



