zoukankan      html  css  js  c++  java
  • Java时间简单操作

    使用java操作时间感觉真真蛋疼,还是我大C#舒服,一个DateTime全部搞定

    这里的Date指的是java.util.Date

    获取当前时间:

            // 创建一个当前时间的Date对象
            Date time = new Date();

    蛋疼的地方,对时间增、减操作:

            // 使用Calendar类对时间增、减操作
            Calendar c = Calendar.getInstance();// 获得一个Calendar实例,该类是抽象类所以不可以使用new构造方法
            // 使用setTime方法创建一个时间,这个time是Date类型
            c.setTime(time);
            // 为当前时间增加12个月,可根据Calendar枚举值改变添加单位
            c.add(Calendar.MONTH, 12);
            // 将Calendar转为Date对象
            Date dateTime = c.getTime();

    再次蛋疼的地方,格式化时间,方便人看的格式:

            // 使用SimpleDateFormat对时间格式化为字符串形式
            String timeStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time);

    简单操作,备忘:

    方便的时间戳转换:

        /**
         * 将时间对象转成时间戳
         * 
         * @param time
         *            时间
         * @return 时间戳
         */
        public static long DateToLong(Date time) {
            try {
                long timeL = time.getTime();
                System.out.print(timeL);
                return timeL;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
    
        }
    
        /**
         * 将时间戳转为时间对象
         * 
         * @param time
         *            时间戳
         * @return 时间对象
         */
        public static Date LongToDate(long time) {
            Date date = null;
            try {
                date = new Date(time);
                System.out.println(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return date;
        }
  • 相关阅读:
    一个简单的window.onscroll实例
    vue 自定义组件使用v-model
    vue开发后台管理系统有感
    cube打包后css顺序错误
    app嵌套的vue项目更新后,页面没有更新
    vue打包后css背景图片地址找不到
    git取消操作命令
    cube-ui indexList的正确使用
    首次db查询时延迟明显高于后面几次。
    git中的merge与rebase
  • 原文地址:https://www.cnblogs.com/kaili/p/4211903.html
Copyright © 2011-2022 走看看