1、字符串转日期
//字符串转日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = null;
try {
dt = sdf.parse(map.get("dt").toString());
} catch (ParseException e) {
e.printStackTrace();
}
//第二种
try {
// 字符串转Date
Date strParseDate = dateFormat.parse("2020-01-01 00:00:00");
// 字符串转Calender 先转为Date再转Calender
Calendar strParseCalendar = Calendar.getInstance();
strParseCalendar.setTime(strParseDate);
} catch (ParseException e) {
e.printStackTrace();
}
日期转字符串
import java.text.SimpleDateFormat;
import java.util.Date;
//日期转字符串
public class Main{
public static void main(String[] args){
Date date = new Date();
String strDateFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println(sdf.format(date));
}
}
字符串转Date
try {
// 字符串转Date
Date strParseDate = dateFormat.parse("2020-01-01 00:00:00");
// 字符串转Calender 先转为Date再转Calender
Calendar strParseCalendar = Calendar.getInstance();
strParseCalendar.setTime(strParseDate);
} catch (ParseException e) {
e.printStackTrace();
}
日期转时间戳
// date转时间戳
Date date = new Date();
long dateTimeStamp = date.getTime();
// Calender转时间戳
Calendar calendar = Calendar.getInstance();
long calTimeStamp = calendar.getTime().getTime();
// String转时间戳
Timestamp ts = Timestamp.valueOf("2020-01-01 00:00:00");
long strTimeStamp = ts.getTime();
// LocalDateTime转时间戳
// 获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
// 获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
时间戳转日期
long timestamp = 1326499860000L;
// 时间戳转Date
Date timeStampDate = new Date(timestamp);
// 时间戳转Calender
Calendar timeStampCalendar = Calendar.getInstance();
timeStampCalendar.setTimeInMillis(timestamp);
// 时间戳转String
String timeStampStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
// 时间戳转LocalDateTime
LocalDateTime timeStampLocalDateTime = LocalDateTime.ofEpochSecond(timestamp,0, ZoneOffset.ofHours(8));