最近接到一个需求就是需要查询指定时间范围内的所有用户信息,而且需要拿到范围内的所有年月字符串~
其实这个并不难,但是数据库中的时间类型是Timestamp类型的,而要求传入的时间类型为Date类型,所以就会涉及到时间类型的转换,这里我就把最近接触到的时间类型之间的转换总结一下,仅供大家参考~
1、StringToDate
@Test
public void testStringToDate() throws ParseException {
String dateStr = "2021-12-10 11:11:11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//java.util包下的Date类;
Date date = sdf.parse(dateStr);
System.out.println(date.toString());
//Fri Dec 10 11:11:11 CST 2021
}
2、DateToString
@Test
public void testDateToString(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(date);
System.out.println(dateStr);
// 2021-12-10 10:22:31
}
3、DateToTimeStamp
@Test
public void testDateToTimeStamp(){
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
System.out.println(timestamp);
// 2021-12-10 10:29:25.978
}
4、TimestampToDate
@Test
public void testTimestampToDate(){
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
System.out.println(date);
// Fri Dec 10 10:30:16 CST 2021
}
5、StringToTimestamp
@Test
public void testStringToTimestamp(){
String dateStr = "2021-12-10 11:11:11";
Timestamp timestamp = Timestamp.valueOf(dateStr);
System.out.println(timestamp);
// 2021-12-10 11:11:11.0
}
6、TimestampToString
@Test
public void testTimestampToString(){
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat();
String s = sdf.format(timestamp);
System.out.println(s);
// 21-12-10 上午10:27
}
7、DateToCalendar
@Test
public void testDateToCalendar(){
Date date = new Date();
Calendar instance = Calendar.getInstance();
instance.setTime(date);
System.out.println(instance.getTime());
// Fri Dec 10 10:36:39 CST 2021
}
8、CalendarToDate
@Test
public void testCalendarToDate(){
Calendar instance = Calendar.getInstance();
Date time = instance.getTime();
System.out.println(time);
// Fri Dec 10 10:56:30 CST 2021
}
其实时间的类型有好多种,但是其实转换还是比较简单。为了方便我们处理时间对象,比如:拿日期中的年份月份等信息,我们还有各种时间工具类,还是很方便的啦~
有些时间类的API已经过时了,大家最好用比较新的API,避免不必要的差值!