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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...