java时间模块
java时间模块
-
获取当前时间戳
public class Demo1 { public static void main(String[] args) { // 获取当前时间戳 long timestamp = System.currentTimeMillis(); System.out.println(timestamp); // (单位毫秒) 1583847471988 } }
-
获取当前时间
import java.util.Date; public class Demo1 { public static void main(String[] args) { // 获取当前时间 Date date = new Date(); System.out.println(date); // Tue Mar 10 21:38:58 CST 2020 } }
-
获取当前格式化时间
import java.util.Date; import java.text.SimpleDateFormat; public class Demo1 { public static void main(String[] args) { // 获取当前时间 Date date = new Date(); System.out.println(date); // Tue Mar 10 21:38:58 CST 2020 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format_time = sdf.format(date); System.out.println(format_time); // 2020-03-10 21:41:00 } }
-
根据时间戳格式化当前时间
import java.util.Date; import java.text.SimpleDateFormat; public class Demo1 { public static void main(String[] args) { long timeStamp = 1583847471009L; SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String sd0 = sdf.format(timeStamp); System.out.println(sd0); // 2020-03-10 21:37:51 String sd2 = sdf.format(new Date(timeStamp)); System.out.println(sd2); // 2020-03-10 21:37:51 } }
-
格式化时间转成时间戳
import java.text.ParseException; import java.util.Date; import java.text.SimpleDateFormat; public class Demo1 { // 抛出一个解析异常类 public static void main(String[] args) throws ParseException { String format_time = "2020-03-10 21:37:51"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date struct_time = sdf.parse(format_time); long timestamp = struct_time.getTime(); System.out.println(timestamp); // } }
-
一周之前的时间
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Demo1 { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE,-7); // 一月之前的时间 // calendar.add(Calendar.MONTH,-1); // 一年前 // calendar.add(Calendar.YEAR,-1); Date day = calendar.getTime(); String before7Days = sdf.format(day); System.out.println(before7Days); } }
-
一周之后的时间
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Demo1 { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE,7); // 一月之后的时间 // calendar.add(Calendar.MONTH,1); // 一年后 // calendar.add(Calendar.YEAR,1); Date day = calendar.getTime(); String before7Days = sdf.format(day); System.out.println(before7Days); } }