java時間處理,獲取當前時間的小時,天,本週周幾,本週週一的日期,本月一號的日期

一、時間轉時間戳spa

public static long strToTimestamp(String dateTimeStr) throws Exception {
        Timestamp time = Timestamp.valueOf(dateTimeStr);
        return time.getTime();
    }

二、時間戳轉時間code

public static String timestampToStr(long timestamp) throws Exception {
        Timestamp ts = new Timestamp(timestamp);
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(ts);
    }

三、時間轉換orm

    public static Map strTimeTomap(String dateTimeStr) throws Exception {
//        Timestamp ts = new Timestamp(timestamp);
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat dsdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();

        Date date = sdf.parse(dateTimeStr);
        cal.setTime(date);
        String week_day = String.valueOf(cal.get(Calendar.DAY_OF_WEEK) - 1);
        String hour = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));

        cal.set(Calendar.DAY_OF_MONTH, 1);
        String first_day_month = dsdf.format(cal.getTime());
//        System.out.println(first_day_month);

        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        String first_day_week = dsdf.format(cal.getTime());
//        System.out.println(first_day_week);

        String day = dsdf.format(date);
        Map map = new HashMap<String,String>();
        map.put("hour",hour);
        map.put("day",day);
        map.put("week_day",week_day);
        map.put("first_day_week",first_day_week);
        map.put("first_day_month",first_day_month);

        return map;
    }

    @Test
    public void test() throws Exception {
        System.out.println(strTimeTomap("2019-04-18 12:31:05"));
    }
相關文章
相關標籤/搜索