zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Java时间处理

2023-03-15 22:05:45 时间

Java时间处理

格式化时间

使用 SimpleDateFormat 类的 format(date) 方法来格式化时间

import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
    public static void main(String[] args){
        Date date = new Date();
        System.out.println("未格式化时间:"+date);
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        System.out.println("格式化时间:"+sdf.format(date));
    }
}
/*
输出结果:
未格式化时间:Thu Jun 04 15:51:47 CST 2020
格式化时间:2020-06-04 15:51:47
*/

获取当前年份月份等

使用 Calendar 类来输出年份、月份等:

import java.util.Calendar;

public class Test{
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int dow = cal.get(Calendar.DAY_OF_WEEK);
        int dom = cal.get(Calendar.DAY_OF_MONTH);
        int doy = cal.get(Calendar.DAY_OF_YEAR);

        System.out.println("当期时间: " + cal.getTime());
        System.out.println("日期: " + day);
        System.out.println("月份: " + month);
        System.out.println("年份: " + year);
        System.out.println("一周的第几天: " + dow);  // 星期日为一周的第一天输出为 1,星期一输出为 2,以此类推
        System.out.println("一月中的第几天: " + dom);
        System.out.println("一年的第几天: " + doy);
    }
}
/*
输出结果:
当期时间: Thu Jun 04 15:53:16 CST 2020
日期: 4
月份: 6
年份: 2020
一周的第几天: 5
一月中的第几天: 4
一年的第几天: 156
*/

时间戳转日期格式

使用 SimpleDateFormat 类的 format() 方法将时间戳转换成时间。

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test{
    public static void main(String[] args) {
        Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));      // 时间戳转换成时间
        System.out.println("格式化结果:" + sd);
    }
}
/* 输出结果:
格式化结果:2020-06-04 15:56:29
*/

日期格式转时间戳

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test{
    public static void main(String[] args) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = "2019-09-16 09:40:19";
        Date date =  sdf.parse(str);
        long time = date.getTime();
        System.out.println(time);
    }
}
/*  输出结果:
1568598019000
*/