Home >Java >javaTutorial >Java method to obtain the specified number of milliseconds and convert it to time format
This article is mainly to solve some problems that everyone encounters in the learning process, so that everyone can understand the time function and understand the time function. Everyone can help.
There are two methods to obtain the millisecond value of the specified time:
1.Calendar class
First obtain the Calendar object through getInstance, and then use the clear method to reset the time to (1970.1.1 00:00: 00), then use the set method to set the specified time, and finally use getTimeMillis to obtain the millisecond value.
public class Time{ public static void main(String[] args){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(2018,0,1); long millis = calendar.getTimeInMillis(); //输出获取的毫秒数 Systeam.out.print(millis); //将其毫秒数转为日期类型 DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); calendar.setTimeInMillis(millis); System.out.println(millis + " = " + formatter.format(calendar.getTime())); } }
2.java.util.Date class SimpleDateFormat class
First create a SimpleDateFormat object from the time format, and then Create a Date object from the specified time through the parse method, and finally obtain the millisecond value through the getTime method of the Date object.
public class Time{ public static void main(String[] args){ SimpleDateFormat sd = new SimpleDateFormat("yyyy-mm-dd"); Date date = null; try { date = format.parse("2018-01-01"); } catch (ParseException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } long millis = date.getTime(); Systeam.out.print(millis); //将其毫秒数转为日期类型 Date date=new Date(millis); System.out.println(sd.format(date)); } }
In comparison, obviously the first method is better: just create an object, you can repeatedly set the time and get the millisecond value. The second method requires creating at least two objects, and a new Date object is created every time a time is set, just for understanding.
This article has ended here. For more exciting content, you can pay attention to the Java Video Tutorial column of the PHP Chinese website!
The above is the detailed content of Java method to obtain the specified number of milliseconds and convert it to time format. For more information, please follow other related articles on the PHP Chinese website!