(1)格式化时间

1 package JavaEE.JavaBaseExampleTest.Date;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 /**
7 * 使用 SimpleDateFormat 类的 format(date) 方法来格式化时间
8 */
9 public class DataFormat {
10 public static void main(String[] args){
11 Date date = new Date();
12 String StrDate = "yyyy-MM-dd HH:mm:ss";
13 SimpleDateFormat sdf = new SimpleDateFormat(StrDate);
14 System.out.println(sdf.format(date));
15 }
16 }
(2)输出年份、月份

1 package JavaEE.JavaBaseExampleTest.Date;
2
3 import java.util.Calendar;
4
5 /**
6 * 使用 Calendar 类来输出年份、月份等
7 */
8 public class GatYearMonthDay {
9 public static void main(String[] args){
10 Calendar cal = Calendar.getInstance();
11 int day = cal.get(Calendar.DATE);
12 int month = cal.get(Calendar.MONTH) + 1;
13 int year = cal.get(Calendar.YEAR);
14 int dow = cal.get(Calendar.DAY_OF_WEEK);
15 int dom = cal.get(Calendar.DAY_OF_MONTH);
16 int doy = cal.get(Calendar.DAY_OF_YEAR);
17
18 System.out.println("当前时间:" + cal.getTime());
19 System.out.println("日期:" + day);
20 System.out.println("月份:" + month);
21 System.out.println("年份:" + year);
22 System.out.println("一周的第几天:" + dow);
23 System.out.println("一月的第几天:" + dom);
24 System.out.println("一年的第几天:" + doy);
25 }
26 }
(3)输出当前时间

1 package JavaEE.JavaBaseExampleTest.Date;
2
3 import java.util.Date;
4 import java.text.SimpleDateFormat;
5
6 /**
7 * 使用 Date 类及 SimpleDateFormat 类的 format(date) 方法来输出当前时间
8 */
9 public class GetData {
10 public static void main(String[] args){
11 SimpleDateFormat sdf = new SimpleDateFormat();
12 sdf.applyPattern("yyyy-MM-dd HH:mm:ss a"); //a 为 am/pm标记
13 Date date = new Date();
14 System.out.println("当前时间:" + sdf.format(date));
15 }
16 }
(4)时间戳转时间

1 package JavaEE.JavaBaseExampleTest.Date;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 /**
7 * 使用 SimpleDateFormat 类的 format() 方法将时间戳转换成时间
8 */
9 public class TimeStampToTime {
10 public static void main(String[] args){
11 //获取当前时间戳
12 Long timeStamp = System.currentTimeMillis();
13 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
14 // 时间戳转换成时间
15 String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
16 System.out.println(sd);
17 }
18 }
来源:https://www.cnblogs.com/skygrass0531/p/12299216.html
