一、日期和字符串互转
package deng;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest01 {
public static void main(String[] args) throws Exception {
//获取时间
Date nowtime=new Date();
System.out.println(nowtime);
/*
* yyyy 年
* MM 月
* dd 日
* HH 时
* mm 分
* ss 秒
* SSS 毫秒
* 注意:在日期格式中,除了y M d H m s S不能随便写,其他字符都是随意组织
* */
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String nowtimstr=sdf.format(nowtime);//Date类型转换为字符串
System.out.println(nowtimstr);
String time="2022-08-08 08:08:08 888";
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
Date datetime=sdf2.parse(time);//字符串转化日期
System.out.println(datetime);
}
}
二、时间戳和字符串之间转换
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test2 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(new Date()));
//获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
long timeStamp = System.currentTimeMillis();
//这个是你要转成后的时间的格式
SimpleDateFormat sdff=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 时间戳转换成时间
String sd = sdff.format(new Date(timeStamp));
System.out.println(sd);//打印出你要的时间
}
/*
* 将时间转换为时间戳
*/
public static String dateToStamp(String s) throws ParseException {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
/*
* 将时间戳转换为时间
*/
public static String stampToDate(String s){
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
}
参考:java中获取日期 日期和字符串互转_每天进步一点点dlb的博客-CSDN博客_java获取当前时间转成字符串
java 获取当前时间并转化为yyyy-MM-dd HH:mm:ss格式 时间戳和字符串之间转换 - sunny123456 - 博客园