Java筆記(一)

来源:https://www.cnblogs.com/vvxtoys/archive/2018/01/06/8215534.html
-Advertisement-
Play Games

最近總是接觸時間處理問題,花了點時間整理以前使用過的方法,修改整合,記錄下來方便以後使用。 package cc.vvxtoys.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java ...


最近總是接觸時間處理問題,花了點時間整理以前使用過的方法,修改整合,記錄下來方便以後使用。

package cc.vvxtoys.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
 * 
 * @author vvxtoys
 * @date 2018年1月6日下午9:48:02
 *
 */
public class DateUtils {
    
    private static  Calendar cal = Calendar.getInstance();
    private static String fm = "";//format month
    private static String fd = "";//format day
    
    
    public static void main(String[] args) throws Exception{
        int year = 2018;
        int month = 2;
        System.out.println(isLeapYear(year));
        System.out.println(getCurrentDate());
        System.out.println(getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        System.out.println(addDays("2018-01-01", 10));
        System.out.println(addMonths("2018-01-31", 1));
        System.out.println(addWeeks("2018-01-03", 1));
        System.out.println(getMonthDays(year, month));
        System.out.println(addYears("2011-09-01", 1));
        System.out.println(getDayOfWeek("2018-01-01"));
        System.out.println(getStartDayOfMonth(year, 2));
        System.out.println(getEndDayOfMonth(year, 2));
        System.out.println(getStartDayOfThisWeek("2018-01-01"));
        System.out.println(getEndDayOfThisWeek("2018-01-01"));
        System.out.println(addQuarters("2018-01-01", 2));
        System.out.println(getWeekOfYear("2018-01-01"));        
        System.out.println(translateDate("2019-01-01", null));
        System.out.println(translateDate(new Date(), null));
        System.out.println(getEndDayOfMonth(year, 2));
        System.out.println(getSubDays(3*3));
        System.out.println(intervalDay("2018-10-10", "2019-01-01"));
        
    }
    /**
     * 
     * @author vvxtoys
     * @param year
     * @return
     * @description 判斷是否為閏年
     */
    public static boolean isLeapYear(int year){
        return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
    }
    /**
     * 
     * @author vvxtoys
     * @param year
     * @param month
     * @return
     * @description 獲取月天數
     */
    public static String getMonthDays(int year,int month){
        String [] days = {"31", null, "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"};
        if(isLeapYear(year)){
            days[1]="29";
        }else{
            days[1]="28";
        }
        return days[month-1];
    } 
    /**
     * 
     * @author vvxtoys
     * @param date
     * @return
     * @throws ParseException
     * @description 獲取時間在當前年為第幾周
     */
    public static int getWeekOfYear(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");      
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        String firstDay = date.substring(0, 4) + "-01-01";
        cal.setTime(sdf.parse(firstDay));
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 2) {
            cal.setTime(sdf.parse(date));
            int num = cal.get(Calendar.WEEK_OF_YEAR);
            return num;
        } else {
            cal.setTime(sdf.parse(date));
            int num = cal.get(Calendar.WEEK_OF_YEAR) - 1;
            return num;
        }
    }
    /**
     * 
     * @author vvxtoys
     * @param date
     * @param num
     * @return
     * @description 天計算
     */
    public static String addDays(String date,int num){
        try{
        cal.setTime(toDate(date));
        cal.add(Calendar.DATE, num);
        toFormatDate();
        }catch(Exception e){
            e.printStackTrace();
        }
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }   
    /**
     * 
     * @author vvxtoys
     * @param date
     * @param num
     * @return
     * @description 星期
     */
    public static String addWeeks(String date,int num){
        try {
            cal.setTime(toDate(date));
            cal.add(Calendar.WEEK_OF_YEAR, num);
            toFormatDate();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }
    /**
     * 
     * @author vvxtoys
     * @param date
     * @param num
     * @return
     * @description 月
     */
    public static String addMonths(String date,int num){
        try {
            cal.setTime(toDate(date));
            cal.add(Calendar.MONTH, num);
            toFormatDate();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }   
    /**
     * 
     * @author vvxtoys
     * @param date
     * @param num
     * @return
     * @description 季度
     */
    public static String addQuarters(String date,int num){
        try {
            cal.setTime(toDate(date));
            cal.add(Calendar.MONTH, num*3);
            toFormatDate();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }   
    /**
     * 
     * @author vvxtoys
     * @param date
     * @param num
     * @return
     * @description 年
     */
    public static String addYears(String date,int num){
        try {
            cal.setTime(toDate(date));
            cal.add(Calendar.YEAR, num);
            toFormatDate();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }
    /**
     * 
     * @author vvxtoys
     * @param time
     * @param pattern
     * @return
     * @description 日期轉換
     */
    public static Object translateDate(Object time, String pattern) {
        Object date = new Object();
        if (isEmpty(pattern)) {
            pattern = "yyyy-MM-dd";
        }
        if (isEmpty(time)) {
            time = "1970-1-1";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            if (time instanceof String) {
                date = sdf.parse((String) time);
            } else if (time instanceof Date) {
                date = sdf.format(time);
            } else {
                throw new Exception("轉換失敗");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }
    /**
     * 
     * @author vvxtoys
     * @param date
     * @return
     * @description 當前日期為本周第幾天
     */
    public static int getDayOfWeek(String date){
        try{
        cal.setTime(toDate(date));
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        }catch(ParseException e){
            e.printStackTrace();
        }
        return cal.get(Calendar.DAY_OF_WEEK)==1?7:cal.get(Calendar.DAY_OF_WEEK)-1;
    }
    /**
     * 
     * @author vvxtoys
     * @param date
     * @return
     * @description 周一
     */
    public static String getStartDayOfThisWeek(String date){
      return addDays(date, -(getDayOfWeek(date)-1));
    }   
    /**
     * 
     * @author vvxtoys
     * @param date
     * @return
     * @description 周日
     */
    public static String getEndDayOfThisWeek(String date){
        return addDays(date,(7-getDayOfWeek(date)));
    }
    //獲取當前時間
    public static String getCurrentDate(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }
    //當前時間
    public static String getCurrentDate(String pattern){
        Date date = new Date();
        if(isEmpty(pattern)){
            pattern = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }   
    /**
     * 
     * @author vvxtoys
     * @param num
     * @return
     * @description 時間間隔  月 季度 年  *3 *12
     */
    public static int getSubDays(int num){
        Date date = new Date();
        cal.setTime(date);
        cal.add(Calendar.MONTH, num);
        long time = cal.getTimeInMillis() - date.getTime();
        return (int) (time / (1000 * 60 * 60 * 24));
    }
    /**
     * 
     * @author vvxtoys
     * @param year
     * @param num
     * @return
     * @description 獲取第幾周開始時間
     */
    public static String getStartDayOfWeek(int year,int num){
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, num);
        toFormatDate();
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }
    /**
     * 
     * @author vvxtoys
     * @param year
     * @param num
     * @return
     * @description 獲取第幾周結束時間
     */
    public static String getEndDayOfWeek(int year,int num){
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, num);
        cal.add(Calendar.DAY_OF_WEEK, 6);
        toFormatDate();
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }
    /**
     * 
     * @author vvxtoys
     * @param year
     * @param num
     * @return
     * @description 獲取第幾月開始時間
     */
    public static String getStartDayOfMonth(int year,int num){
        String month = num < 10 ? "0" + num : String.valueOf(num);
        return year + "-" + month + "-" + "01";
    }
    /**
     * 
     * @author vvxtoys
     * @param year
     * @param num
     * @return
     * @description 獲取第幾月結束時間
     */
    public static String getEndDayOfMonth(int year,int num){
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, num - 1);
        cal.set(Calendar.DATE, 1);
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        toFormatDate();
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }
    //獲取第幾季度開始時間
    public static String getStartDayOfQuarter(int year,int num){
        num = 3 * num - 2;
        String month = num < 10 ? "0" + num : String.valueOf(num);
        return year + "-" + month + "-" + "01";
    }
    //獲取第幾季度結束時間
    public static String getEndDayOfQuarter(int year,int num){
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, 3 * num - 1);
        cal.set(Calendar.DATE, 1);
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        toFormatDate();
        return cal.get(Calendar.YEAR) + "-"+fm+"-"+fd;
    }
    //時間間隔
    public static int intervalDay(String d1,String d2){
        int num = 0;
        try{
        long second = toDate(d2).getTime()-toDate(d1).getTime();
        num=(int)(Math.abs(second)/(1000 * 60 * 60 * 24));
        }catch(ParseException e){
            e.printStackTrace();
        }
        return num;
    }
    private static void toFormatDate(){
        int month = (cal.get(Calendar.MONTH) + 1);
        fm = month<10?"0"+month:String.valueOf(month);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        fd = day<10?"0"+day:String.valueOf(day);    
    }   
    private static Date toDate(String date) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(date);
    }
    private static boolean isEmpty(Object obj){
        return obj==null||obj.toString().trim().equals("");
    }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.前言 光陰似箭,日月如梭。不得不感慨時間過得很快,2017差不多結束了,一下子我從事前端開發的時間已經兩年了。這兩年可以說是一波三折,回想這兩年的經歷,讓我忍不住了寫下了這篇文章,記錄自己在這兩年經歷的種種種種。這篇文章,打算當做自己的一個經歷記錄,而對於看這篇文章的你,希望你們能從我的經歷裡面 ...
  • <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.Random"%> <%@ page import="java.io.O ...
  • package cn.itcast.bos.utils; import java.util.Arrays; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyin ...
  • 1.install一個npm包的時候,總是會報這個警告; 網上查資料知道,這個fsevents是mac下用的,windows忽略即可; 2.關於在main.js中引入less文件的問題, 就會報這個錯,說相關模塊沒有找到,這個問題,我在網上找了很多資料,然後我也都試了,都不好用,於是我的解決辦法就是 ...
  • 現效果如下: 由於我這邊不需要其他按鈕,就沒寫 數據是由後臺提供,在這做了個小列子 後臺代碼 頁面代碼 Js ...
  • 期末,要交一個大作業,正巧之前跑國圖借書的時候,暈頭轉向的,國圖內居然沒有導航!!!借這個機會做一個室內導航的demo,只是半成品,還需要加入室內定位,匹配一下坐標才能在實際中使用。 demo:利用蜂鳥雲平臺進行二次開發實現。愛琴海商城內部尋徑。 主要功能: 代碼!不給~ 上圖!! 初始界面 查找終 ...
  • 定義求最大最小值的函數 輸入為: ...
  • 上面這段代碼一直在用,面試的時候也經常被問到,卻從未深究過,不知道線程池到底是怎麼回事,今天看看源代碼,一探其究竟 線程池主要控制的狀態是ctl,它是一個原子的整數,其包含兩個概念欄位: workerCount:有效的線程數量 runState:線程池的狀態 為了在一個整型值裡面包含這兩個欄位,我們 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...