美文网首页
java 日期时间的实例练习

java 日期时间的实例练习

作者: 月圆星繁 | 来源:发表于2021-02-03 23:41 被阅读0次
  • java 日期时间的实例练习:
package com.mgk.time;

import javax.swing.plaf.synth.SynthUI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateFormat {
    public static void main(String[] args) {
        // 使用SimpleDateFormat()类的format(date)方法格式化时间
        Date date = new Date();
        System.out.println("date:" + date); // date:Sun Jan 31 16:35:33 CST 2021
        String dateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        System.out.println( sdf.format(date)); // 2021-01-31 16:35:33

        // 1.获取当前时间
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = sdf2.format(new Date());
        System.out.println( nowTime ); //2021-01-31 16:35:34
        // 2.当前时间
        SimpleDateFormat sdf3 = new SimpleDateFormat(); // 格式化时间
        sdf3.applyPattern("yyyy-MM-dd HH:mm:ss a"); // a为am/pm的标记
        System.out.println( sdf3.format(new Date() )); //2021-01-31 16:35:34 下午

        // 获取年份、月份
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH);
        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()); //当前时间:Sun Jan 31 16:35:34 CST 2021
        System.out.println("日期:" + day); //日期:31
        System.out.println("月份:" + month); //月份:0
        System.out.println("年份:" + year); // 年份:2021
        System.out.println("一周的第几天:" + dow); //星期日为一周的第一天为1.周一为2 //一周的第几天:1
        System.out.println("一个月的第几天:" + dom); //一个月的第几天:31
        System.out.println("一年中的第几天:" + doy); //一年中的第几天:31

        // 时间戳转换成时间
        Long timeStamp = System.currentTimeMillis(); // 获取当前时间戳
        System.out.println( "当前时间戳:" + timeStamp); // 当前毫秒时间戳:1612082134015
        System.out.println( "当前时间戳:" + timeStamp/1000); // 当前时间戳:1612082134015
        SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf4.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
        System.out.println( "时间戳转换时间格式结果:" + sd); // 2021-01-31 16:43:50

        SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        String sd2 = sdf5.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
        System.out.println("时间戳转换时间格式结果:" + sd2); // 2021年01月31日 16时43分50秒

    }
}

相关文章

网友评论

      本文标题:java 日期时间的实例练习

      本文链接:https://www.haomeiwen.com/subject/ccretltx.html