java 抓取公众号文章

 maven 依赖

<dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.17.1</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.htmlunit</groupId>
            <artifactId>htmlunit</artifactId>
            <version>2.55.0</version>
        </dependency>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.8.3</version>
        </dependency>

        <dependency>
            <groupId>jnetpcap</groupId>
            <artifactId>jnetpcap</artifactId>
            <version>1.4.r1425-1g</version>
        </dependency>

解析文章核心类

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.cookie.Cookie;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
@Slf4j
public class WxPipeline {

    @Autowired
    UploadFileUtils uploadFileUtils;

    @Value("${temp.upload}")
    String TEMP_UPLOAD_PATH;

    @Autowired
    ConfigMapper configMapper;
    /***            : 初始化
         *@funcName     : getReportDetail
         *@description  : description
         *@return       : String[]
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 13:51
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 13:51
         ***/
    static String[] userAgent = {
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
            "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0",
            "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
            "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
            "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
            "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
            "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
            "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
            "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
            "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
            "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
            "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
            "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
            "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
            "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
            "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
            "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)",
            "UCWEB7.0.2.37/28/999",
            "NOKIA5700/ UCWEB7.0.2.37/28/999",
            "Openwave/ UCWEB7.0.2.37/28/999",
            "Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999",
            "Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25",
    };

    static BrowserVersion browser = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.CHROME)
            .setUserAgent(userAgent[new Random().nextInt(userAgent.length)])
            .build();

    private static final WebClient webClient = new WebClient(browser);
    
    /***            : TODO
         *@funcName     : getReportDetail
         *@description  : description
         *@Param1       : java.lang.String  healthDocUrl
         *@return       : ResponseVO
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 14:03
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 14:03
         ***/
    public Map<String,Object> process(String healthDocUrl) {

        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        HtmlPage pageTmp = null;
        String pageXml = "";
        try {

//            if(healthDocUrl.contains("token=")){
//                try {
//                    pageXml = getHtml(healthDocUrl);
//                    if(StringUtils.isNotEmpty(pageXml)){
//                        pageXml = pageXml.replaceAll("reportloaderror","").replaceAll("&","&amp;");
//
//                    }
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//            }else{
                pageTmp = webClient.getPage(healthDocUrl);
                pageXml = pageTmp.asXml();
//            }


        } catch (Exception e) {

            log.error("解析文章链接出错,文章地址:{},错误信息:{}",healthDocUrl,e.getMessage());
        } finally {
            webClient.close();
        }

        HealthDocEntity healthDoc = domParserXML(pageXml);
        String mediaId = setHealthDocMediaId(healthDocUrl);
    //    String mediaId = SnowflakeIdUtil.getNextId("HDC");
        if(null != healthDoc){
            healthDoc.setMediaId(mediaId);
        }
        Map<String,Object> result = new HashMap<>();
        result.put("pageXml",pageXml);
        result.put("healthDoc",healthDoc);
        return result;
    }

    /***            : 直接获取不规范链接网页
         *@funcName     : getReportDetail
         *@description  : description
         *@Param1       : java.lang.String  target
         *@Param2       : java.lang.String  registerEntity
         *@return       : ResponseVO
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-23 16:22
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-23 16:22
         ***/
    public String getHtml(String healthDocUrl) throws Exception {

        URL url = new URL(healthDocUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            connection.disconnect();
            return content.toString();
        } else {
            throw new Exception("Failed to get HTML content, response code: " + connection.getResponseCode());
        }

    }


    /***            : 截取链接中的最后一个斜杠后的内容,用作文章的编号
         *@funcName     : setHealthDocMediaId
         *@description  : description
         *@Param1       : java.lang.String  healthDocUrl
         *@return       : String
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 13:47
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 13:47
         ***/
    private String setHealthDocMediaId(String healthDocUrl) {

        if(!StringUtils.isEmpty(healthDocUrl)){
            return healthDocUrl.substring(healthDocUrl.lastIndexOf("/")+1);
        }
        return null;

    }

    private HealthDocEntity domParserXML(String pageXml){
        HealthDocEntity healthDoc = new HealthDocEntity();

        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder = factory.newDocumentBuilder();

            Document document = builder.parse(new ByteArrayInputStream(pageXml.getBytes(StandardCharsets.UTF_8)));
            //根据body标签名称获取被body标签包裹的html
            Node jsArticle = findNodeById(document.getDocumentElement(), null,"body");
            String title = getNode(jsArticle,"activity-name");
            String content = jsoupHtml(pageXml,"js_content");
            String author = getNode(jsArticle,"js_name");

            List<String> imageUrls = jsoupImg(pageXml,"js_content","img");
            String publishTime = getNode(jsArticle,"publish_time");
            healthDoc.setAuthor(author.trim());
            healthDoc.setTitle(title.trim());
            healthDoc.setThumbUrls(imageUrls);
            healthDoc.setContent(content);
            healthDoc.setCreateTime(DateUtil.chineseFormat(publishTime.trim()));
            return healthDoc;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章解析失败!{}",e.getMessage());
        }
        return null;
    }

    /***            : 获取指定html 中的指定id的标签包裹的html内容
         *@funcName     : jsoup
         *@description  : description
         *@Param1       : java.lang.String  htmlString
         *@Param2       : java.lang.String  id 标签id
         *@Param2       : java.lang.String  tagName 标签名
         *@return       : String
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 10:10
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 10:10
         ***/
    public String jsoupHtml(String htmlString,String id){
        org.jsoup.nodes.Document document = Jsoup.parse(htmlString);

        org.jsoup.nodes.Element foundElement = document.getElementById(id);

        return foundElement.outerHtml();
    }


    public List<String> jsoupImg(String htmlString,String id,String tagName) throws IOException {

        org.jsoup.nodes.Document document = Jsoup.parse(htmlString);
        org.jsoup.nodes.Element foundElement = document.getElementById(id);
        org.jsoup.select.Elements elements = foundElement.select(tagName);
        return getValueElement(elements);
    }

    /***            : 获取html中的某个标签内包含的所有图片
         *@funcName     : getValueElement
         *@description  : description
         *@Param1       : org.jsoup.select.Elements  imgTags
         *@return       : String
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 13:15
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 13:15
         ***/
    public List<String> getValueElement(org.jsoup.select.Elements imgTags) throws IOException {

        List<String> tagNameValue = new ArrayList<>();

        if (!imgTags.isEmpty()) {

            for (org.jsoup.nodes.Element img : imgTags) {
                String imgSrc = img.attr("data-src"); // Get the src attribute
                if(tagNameValue.size()<=2){

                    tagNameValue.add(StringUtils.isEmpty(imgSrc)?imgSrc:imgSrc.trim());
//                    URL url = new URL(StringUtils.isEmpty(imgSrc)?imgSrc:imgSrc.trim());
//                    InputStream in = url.openStream();
//
//                    byte[] bytes = IOUtils.toByteArray(in);
//                    String fileName = UUID.randomUUID().toString()+".png";
//                    // 导出路径和文件格式
//
//                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
//                    String today = format.format(new Date()); // 今日日期
//                    String dirStr = TEMP_UPLOAD_PATH + today;
//                    String imgPath = System.getProperty("user.dir") +  TEMP_UPLOAD_PATH + today + "/";
//                    List<ConfigEntity> configEntities = configMapper.selectAll();
//                    String serverIp = configEntities.get(0).getConfigValue();
//                    String popup_image_path = configEntities.get(2).getConfigValue();
//                    String returnPath =  today + "/" + fileName;
//                    Path path = Paths.get(dirStr);
//                    if(!Files.exists(path)){ // 查看是否存在文件夹
//                        Files.createDirectory(path);
//                    }
//                    FileUtils.writeByteArrayToFile(new File(imgPath+fileName),bytes);
//                    log.debug("上传的图片放温暖路径:{}",serverIp + popup_image_path + returnPath);
                    log.debug("图片上传完成");
                }else{
                    return tagNameValue;
                }

            }
        }

        return tagNameValue;
    }


    /***            : TODO
         *@funcName     : getReportDetail
         *@description  : description
         *@Param1       : Node node
         *@Param2       : java.lang.String  elementId
         *@return       : String
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 9:05
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 9:05
         ***/
    public String getNode(Node node,String elementId){

        return Objects.requireNonNull(findNodeById(node, elementId,null)).getTextContent();
    }
    
    /***            : TODO
         *@funcName     : findNodeById
         *@description  : description
         *@Param1       : Node node
         *@Param2       : java.lang.String  id
         *@Param2       : java.lang.String  tagName
         *@return       : Node
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 9:05
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 9:05
         ***/
    private static Node findNodeById(Node node, String id,String tagName) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
//            System.out.println(element.getTagName());
            if (element.getAttribute("id").equals(id) || (!StringUtils.isEmpty(tagName) && tagName.equals(element.getTagName()))) {
                return element;
            }
        }

        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node foundNode = findNodeById(childNodes.item(i), id,tagName);
            if (foundNode != null) {
                return foundNode;
            }
        }

        return null;
    }

}

 时间工具类

@Slf4j
public class DateUtil {

    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYY_MM_DD_HH = "yyyy-MM-dd HH";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYMMDDHHMMSS = "yyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD_T_HH_MM_SS_SSS = "yyyy-MM-ddTHH:mm:ss";
    public static String YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};


    /**
     * 获取当前时间
     *
     * @return
     */
    public static Date now() {
        return new Date();
    }

    /**
     * 获取当前日期,默认格式为 yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String getTimeHHMM() {
        return dateTimeNow(YYYY_MM_DD_HH_MM);
    }



    public static final String getTimeHH(){return dateTimeNow(YYYY_MM_DD_HH);}

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String dateTimeHHMMSS(final Date date) {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
    }


    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    public static final String dateSame(String sameTime) throws ParseException {

        SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD);
        Date sameDate = dateFormat.parse(sameTime);

        return DateFormatUtils.format(sameDate, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如 20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }



    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static String getDateStr(Date dateParam){
        //Date currentDate = new Date();
        // 创建 SimpleDateFormat 实例,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化日期为字符串
        String formattedDate = sdf.format(dateParam);
        return formattedDate;
    }


    public static String getNowDate(){
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 实例,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化日期为字符串
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }

    public static String getShortNowDate(){
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 实例,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat(YYMMDDHHMMSS);
        // 格式化日期为字符串
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }



    public static String getNowDateStr(){
        LocalDateTime currentDate = LocalDateTime.now();
        //Date currentDate = new Date();
        // 创建 SimpleDateFormat 实例,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化日期为字符串
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }

    public static String getNowDateToSecond(){
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 实例,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 格式化日期为字符串
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }

    public static LocalDate stringToLocalDate(String dateString){

        if(!StringUtils.isEmpty(dateString)){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD);

            return LocalDate.parse(dateString, formatter);
        }else{
            return null;
        }
    }

    public static LocalDateTime stringToLocalDateTime(String dateString){

        if(!StringUtils.isEmpty(dateString)){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);

            return LocalDateTime.parse(dateString, formatter);
        }else{
            return null;
        }
    }
    public static LocalDateTime stringToLocalDateTimeH(String dateString){

        if(!StringUtils.isEmpty(dateString)){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);

            return LocalDateTime.parse(dateString, formatter);
        }else{
            return null;
        }
    }

    public static LocalDate stringToLocalDateymdhms(String dateString){

        if(!StringUtils.isEmpty(dateString)){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);

            return LocalDate.parse(dateString, formatter);
        }else{
            return null;
        }
    }
    public static Date addOneYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1);
        return calendar.getTime();
    }
    public static Date stringToDateTime(String dateString){
        SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        if(!StringUtils.isEmpty(dateString)){

            // 格式化日期为字符串
            Date date = null;
            try {
                return  dateFormat.parse(dateString);
            } catch (ParseException e) {
                DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateString, formatter);
                LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
                ZoneId zoneId = ZoneId.systemDefault();
                Date date1 = Date.from(localDateTime.atZone(zoneId).toInstant());
                return date1 ;
            }
        }else{
            return null;
        }
    }

    public static Date tStringToDateTime(String dateString) {
        if(com.baiyue.base.util.StringUtils.isNotEmpty(dateString)) {
            LocalDateTime localDateTime = LocalDateTime.parse(dateString);
            ZoneId zoneId = ZoneId.systemDefault();
            Date date = Date.from(localDateTime.atZone(zoneId).toInstant());

            SimpleDateFormat targetFormatter = new SimpleDateFormat(YYYY_MM_DD);
            targetFormatter.format(date) ;
            return date;
        }

        return new Date() ;
    }

    public static Date localStringToDate(String dateString) {
        if (!StringUtil.isEmpty(dateString)) {
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
            SimpleDateFormat targetFormatter = new SimpleDateFormat(YYYY_MM_DD);
            Date date = new Date() ;
            try {
                date = formatter.parse(dateString);

                //System.out.println(date);

                //return date;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }



        return new Date();
    }

    public static Date longStringToDateTime(String dateString){
        SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS_SSS);
        if(!StringUtils.isEmpty(dateString)){

            // 格式化日期为字符串
            Date date = null;
            try {
                return  dateFormat.parse(dateString);
            } catch (ParseException e) {
                DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateString, formatter);
                LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
                ZoneId zoneId = ZoneId.systemDefault();
                Date date1 = Date.from(localDateTime.atZone(zoneId).toInstant());
                return date1 ;
            }
        }else{
            return null;
        }
    }

    public static Date stringToDate(String dateString) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            // Parse the string into a Date object
            Date date = dateFormat.parse(dateString);
            return date;
        } catch (ParseException e) {
            String date = dateFormat.format(new Date());
            return dateFormat.parse(date);
        }
    }

    public static Date stringToDateHHss(String dateString) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss");

        try {
            // Parse the string into a Date object
            Date date = dateFormat.parse(dateString);
            return date;
        } catch (ParseException e) {
            String date = dateFormat.format(new Date());
            return dateFormat.parse(date);
        }
    }
    public static String getNowDateToSecond2(){
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 实例,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        // 格式化日期为字符串
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }

    public static String getNowDateToSecond3(){
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 实例,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        // 格式化日期为字符串
        String formattedDate = sdf.format(currentDate);
        return formattedDate;
    }

    public static String getNextYearToday(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 1);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(calendar.getTime());
    }


    public static long getTimeDifference(LocalDateTime createTime) {
        Duration duration = Duration.between(createTime, LocalDateTime.now());

        return duration.toHours();

    }

    public static long getDateTimeDifference(Date date){
        Date now = new Date();
        long differenceInMillis = Math.abs(date.getTime() - now.getTime());
        long differenceInHours = differenceInMillis / (1000 * 60 * 60); // Convert milliseconds to hours

        return differenceInHours;
    }

    public static int getNowYear(){
        return LocalDate.now().getYear();
    }

    /***            : first 时间是否在 second 时间之前,
         *@funcName     : compareDateBefore
         *@description  : description
         *@Param1       : java.lang.String  first
         *@Param2       : java.lang.String  second
         *@return       : boolean
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-04-29 13:32
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-04-29 13:32
         ***/
    public static boolean compareDateBefore(String first,String second){
        SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD);

        try {
            Date date1 = dateFormat.parse(first);
            Date date2 = dateFormat.parse(second);

            return date1.before(date2);
        } catch (Exception e) {
            log.debug("比较时间出错:{}",e.getMessage());
            return false;
        }
    }

    /***            : 判断字符串时间 增加一年是否在Date之前
         *@funcName     : compareStringDateBefore
         *@description  : description
         *@Param1       : java.lang.String  time
         *@Param2       : java.lang.String  date
         *@return       : ResponseVO
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-07-25 13:17
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-07-25 13:17
         ***/
    public static boolean compareStringDateBefore(String time,Date date){

        return compareDateBefore(getDateStr(addOneYear(stringToDateTime(time))),getDateStr(date));
    }

    public static String turnZtime(String dateTimeString){
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        SimpleDateFormat outputFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);

        try {
            Date date = inputFormat.parse(dateTimeString);
            outputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            String formattedDateTime = outputFormat.format(date);
            log.debug("Formatted date and time:{}",formattedDateTime);
            return formattedDateTime;
        } catch (Exception e) {
            log.debug("Error occurred:{}" , e.getMessage());
        }
        return null;
    }

    public static String turnTime(String dateTimeString){

        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        SimpleDateFormat outputFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);

        try {
            Date date = inputFormat.parse(dateTimeString);
            outputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            String formattedDateTime = outputFormat.format(date);
            log.debug("Formatted date and time:{}",formattedDateTime);
            return formattedDateTime;
        } catch (Exception e) {
            log.debug("Error occurred:{}" , e.getMessage());
        }
        return null;
    }

    public static String turnTimeHh(String dateTimeString){

        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat(YYYY_MM_DD_HH);

        try {
            Date date = inputFormat.parse(dateTimeString);
            outputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            String formattedDateTime = outputFormat.format(date);
            log.debug("Formatted date and time:{}",formattedDateTime);
            return formattedDateTime;
        } catch (Exception e) {
            log.debug("Error occurred:{}" , e.getMessage());
        }
        return null;
    }

    public static String turnTimeHhMm(String dateTimeString){

        try {

        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");

        // 解析日期时间字符串
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, inputFormatter);
            // 将 ZonedDateTime 转换为中国标准时间的 ZonedDateTim
            ZonedDateTime targetZonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
            LocalDateTime localDateTime = targetZonedDateTime.toLocalDateTime();
            // 将 ZonedDateTime 转换为 LocalDateTime
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // 格式化日期时间
        String formattedDateTime = localDateTime.format(outputFormatter);
        log.debug("Formatted date and time:{}",formattedDateTime);
        return formattedDateTime;
        } catch (Exception e) {
            log.debug("Error occurred:{}" , e.getMessage());
        }
        return null;
    }

    /***            : 传入的 dateString 时间 距离当前时间天数
         *@funcName     : sameTimeToNowCountDayNum
         *@description  : description
         *@Param1       : java.lang.String  dateString
         *@return       : ResponseVO
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-07-23 9:07
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-07-23 9:07
         ***/
    public static long sameTimeToNowCountDayNum(String dateString){

        if(com.baiyue.base.util.StringUtils.isEmpty(dateString)){
            return 0L;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);

        LocalDate specifiedDate = LocalDate.parse(dateString, formatter);

        LocalDate currentDate = LocalDate.now();

        return ChronoUnit.DAYS.between(specifiedDate, currentDate);
    }

    /***            : 传入的 dateString 时间 距离当前时间年数
     *@funcName     : sameTimeToNowCountDayNum
     *@description  : description
     *@Param1       : java.lang.String  dateString
     *@return       : ResponseVO
     *@version      :
     *@author       : LiZhen
     *@date         : 2024-07-23 9:07
     *@revision     : Ver1.0
     *@reviser      : LiZhen
     *@reviseDate   : 2024-07-23 9:07
     ***/
    public static long sameTimeToNowCountYearNum(String dateString){

        if(com.baiyue.base.util.StringUtils.isEmpty(dateString)){
            return 0L;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);

        LocalDate specifiedDate = LocalDate.parse(dateString, formatter);

        LocalDate currentDate = LocalDate.now();

        return ChronoUnit.YEARS.between(specifiedDate, currentDate);
    }

    public static long sameDateToNowCountDayNum(Date dateString){

        if(ObjectUtils.isEmpty(dateString)){
            return 0L;
        }
        Instant instant = dateString.toInstant();

        LocalDate specifiedDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();;

        LocalDate currentDate = LocalDate.now();

        return ChronoUnit.DAYS.between(specifiedDate, currentDate);
    }

    public static String turnTime2(String dateTimeString) throws ParseException {

        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy/MM/dd");

        Date date = inputFormat.parse(dateTimeString);
        outputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String formattedDateTime = outputFormat.format(date);
        log.debug("Formatted date and time:{}",formattedDateTime);
        return formattedDateTime;

    }

    public static LocalDate dateTurnLocalDate(Date date){

        if(date == null){
            return null;
        }else{
            return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        }

    }

    public static Date localDateTurnDate(LocalDate localDate){

        if(localDate == null){
            return null;
        }else{
            return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        }

    }

    public static String dateFromSeconds(Long seconds){
        Date date = new Date();
        date.setTime(seconds);
        return setDateFormat(date);
    }

    public static String setDateFormat(Date date){
        return new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(date);
    }

    /***            : 把时间yyyy年MM月dd日 HH时mm分 格式化成yyyy-MM-dd HH:mm:ss
         *@funcName     : getReportDetail
         *@description  : description
         *@Param1       : java.lang.String  target
         *@Param2       : java.lang.String  registerEntity
         *@return       : ResponseVO
         *@version      :
         *@author       : LiZhen
         *@date         : 2024-08-16 15:07
         *@revision     : Ver1.0
         *@reviser      : LiZhen
         *@reviseDate   : 2024-08-16 15:07
         ***/
    public static String chineseFormat(String inputDate){
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm");

        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime dateTime = LocalDateTime.parse(inputDate, inputFormatter);

        return dateTime.format(outputFormatter);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值