首页 > 其他分享 >LocalDate、LocalDateTime的用法与String互转

LocalDate、LocalDateTime的用法与String互转

时间:2023-09-14 10:15:54浏览次数:37  
标签:String System println formatDate 互转 LocalDate out

一、LocalDate常用用法

1.1、申明定义

LocalDate formatDate = LocalDate.of(2020, 2, 5); // 自定义
LocalDate today = LocalDate.now(); // 获取当前日期

1.2、getX() 获取年月日等

注意:获取月份使用getMonthValue()

System.out.println(formatDate.getMonth()); // FEBRUARY 获取所在月份(英文)
System.out.println(formatDate.getMonthValue()); // 2 获取所在月份(英文)
System.out.println(formatDate.getDayOfMonth()); // 5 获取所在天

1.3、plusX()、minusX()

LocalDate nextDay = formatDate.plusDays(1);
System.out.println(nextDay); // 2020-02-06 明天
LocalDate nextWeek = formatDate.plusWeeks(1);
System.out.println(nextWeek); // 2020-02-12 下周当天
LocalDate lastMonth = formatDate.minusMonths(1);
System.out.println(lastMonth); // 2020-01-05 上月当天

1.4、扩展用法

常用于报表中计算同比环比等日期

// 同环比日期计算
LocalDate firstWeekDay = formatDate.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
System.out.println(firstWeekDay); // 2020-02-03 本周第一天
LocalDate firstMonthDay = formatDate.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(firstMonthDay); // 2020-02-01 本月第一天
LocalDate firstYearDay = formatDate.with(TemporalAdjusters.firstDayOfYear());
System.out.println(firstYearDay); // 2020-01-01 本年第一天
// 判断两个日期前后
boolean param = formatDate.isBefore(today);
System.out.println(param); // true 判断a是否早于b
// 计算两个日期的间隔天数
LocalDate start = LocalDate.parse("2019-12-01");
LocalDate end = LocalDate.parse("2020-02-05");
long days = start.until(end, ChronoUnit.DAYS);
System.out.println("days: " + days); // days: 66

二、LocalDate与String互转

2.1、LocalDate转String

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate formatDate = LocalDate.of(2020, 2, 5);
String dateStr = formatDate.format(df);
System.out.println("LocalDate => String: " + dateStr);

2.2、String转LocalDate

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateParam = LocalDate.parse(dateStr, df);
System.out.println("String => LocalDate: " + dateParam);

2.3 固定格式输出时间字符串

    /**
     * 时间截取--日
     */
    private String timeSubStringDay(LocalDateTime sendTime) {
        String localDateTimeStr = sendTime.format(DateTimeFormatter.ofPattern("MM-dd     HH:mm"));
        return localDateTimeStr;
    }

三、代码实践

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
 
/**
 * LocalDate日期转换
 *
 * @author: Tansj
 * @since: 2020/02/08
 */
public class Test {
 
    public static void main(String[] args) {
        LocalDate formatDate = LocalDate.of(2020, 2, 5);
        LocalDate today = LocalDate.now();
        System.out.println(formatDate); // 2020-02-05 当天
        System.out.println(today); // 2020-02-08 本日当天
        boolean param = formatDate.isBefore(today);
        System.out.println(param); // true 判断a是否早于b
        System.out.println("=========================================");
        System.out.println(formatDate.getMonth()); // FEBRUARY 获取所在月份(英文)
        System.out.println(formatDate.getMonthValue()); // 2 获取所在月份(数字)
        System.out.println(formatDate.getDayOfMonth()); // 5 获取所在天
        System.out.println("=========================================");
        LocalDate nextDay = formatDate.plusDays(1);
        System.out.println(nextDay); // 2020-02-06 明天
        LocalDate nextWeek = formatDate.plusWeeks(1);
        System.out.println(nextWeek); // 2020-02-12 下周当天
        LocalDate lastMonth = formatDate.minusMonths(1);
        System.out.println(lastMonth); // 2020-01-05 上月当天
        System.out.println("=========================================");
        LocalDate firstWeekDay = formatDate.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
        System.out.println(firstWeekDay); // 2020-02-03 本周第一天
        LocalDate firstMonthDay = formatDate.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println(firstMonthDay); // 2020-02-01 本月第一天
        LocalDate firstYearDay = formatDate.with(TemporalAdjusters.firstDayOfYear());
        System.out.println(firstYearDay); // 2020-01-01 本年第一天
        System.out.println("=========================================");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = formatDate.format(df);
        System.out.println("LocalDate => String: " + dateStr); // LocalDate => String: 2020-02-05
        LocalDate dateParam = LocalDate.parse(dateStr, df);
        System.out.println("String => LocalDate: " + dateParam); // String => LocalDate: 2020-02-05
        LocalDate start = LocalDate.parse("2019-12-01");
        LocalDate end = LocalDate.parse("2020-02-05");
        long days = start.until(end, ChronoUnit.DAYS);
        System.out.println("days: " + days); // days: 66
    }
}

获取日期中的字符串 如"02-03"

String time = hydrologyVO.getSendTime().format(DateTimeFormatter.ofPattern("MM-dd"));

四、LocalDateTime与String、Long互转

2.1、LocalDateTime与String互转

LocalDateTime localDateTime=LocalDateTime.parse(dates,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String localDateTimeStr=LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

2.2、LocalDateTime与Long互转

Long localDateTimeLong=Timestamp.valueOf(LocalDateTime.now()).getTime();
LocalDateTime localDateTimeLongTime=LocalDateTime.ofInstant(Instant.ofEpochMilli(localDateTimeLong)

示例:

 
public static void main(String[] args) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.now();
        String dateStr = localDateTime.format(fmt);
        System.out.println(dateStr);
    }
原文链接:https://blog.csdn.net/qq_34471241/article/details/121104081

标签:String,System,println,formatDate,互转,LocalDate,out
From: https://www.cnblogs.com/doubleflower/p/17701748.html

相关文章

  • String与StringBuffer
    string与stringbuffer都是通过字符数组实现的。其中string的字符数组是final修饰的,所以字符数组不可以修改。stringbuffer的字符数组没有final修饰,所以字符数组可以修改。string与stringbuffer都是final修饰,只是限制他们所存储的引用地址不可修改。至于地址所指内容能不能修......
  • String、StringBuffer和StringBuilder的区别,ArrayList和linkedList的区别,HashMap和Has
    一、String、StringBuffer和StringBuilder的区别1.1相关介绍String是只读字符串,并不是基本数据类型,而是一个对象。从底层源码来看是一个final修饰的字符数组,所引用的字符串不能改变,一经定义无法再增删改。每次对String操作都会生成新的String对象。所以对于经常改变内容的字符串最......
  • PostCSS received undefined instead of CSS string
    问题npmrunserve启动项目后,报错SyntaxError:Error:PostCSSreceivedundefinedinsteadofCSSstring解决node-sass版本兼容问题导致,按照应用使用的node-sass版本切换(可使用nvm)到对应的node版本,再重新npmi......
  • Working With Strings In Python.
    #字符串操作在Python中,`string`是一种不可变的数据类型,用于表示文本或字符序列,可以使用单引号或双引号将字符串括起来。<fontcolor="#C7EDCC">所有修改和生成字符串的操作的实现方法都是另一个内存片段中新生成一个字符串对象。</font>##创建字符串```pystr1="Lefti......
  • How to fix Node.js fs.readFileSync toString Error All In One
    HowtofixNode.jsfs.readFileSynctoStringErrorAllInOneSyntaxError:UnexpectedendofJSONinput❌errorfs.writeFile&fs.readFileSync匹配错误asyncappendFile(group){console.log(`append`)constfile=path.join(__dirname+`/vide......
  • Python数据类型之字符串(String)
    Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。Python中常用的数据类型有6种,分别是:数字(Number)、字符串(String)、列表(List)、元组(Tuple)、字典(Dictionary)、集合(Set)。字符串(String)Python中的字符串用单引号''或者双引号""括起......
  • java.lang.ClassCastException: java.sql.Timestamp cannot be cast to java.lang.Str
    这个问题来自于想把从数据库查询的数据转化为字符串,方便后面做时间比较,显示格式转化错误 sql改造部分 as的左边为我的sql语句语法使用如下DATE_FORMAT((sql语句),'%Y-%m-%d%H:%i:%s')如果是涉及时间的计算,可以考虑如下方式BigDecimala=(BigDecimal)sprint......
  • C++的String与UF8互转
    UTF8_To_String#include<Stringapiset.h>#include<iostream>std::stringUTF8_To_String(conststd::string&str){intnwLen=MultiByteToWideChar(CP_UTF8,0,str.c_str(),-1,NULL,0);wchar_t*pwBuf=newwchar_t[nwLen+1];//一定要加......
  • JSON.stringify和JSON.parse的用法和区别
    JSON.stringify()和JSON.parse()是JavaScript中用于处理JSON数据的方法,它们的用法和区别如下:####一:JSON.stringify()方法将JavaScript对象或值转换为JSON字符串。它接受一个参数,即要转换的对象或值。示例:varobj={name:'John',age:25};varjsonString=JSON.......
  • Java常用类-String
    String保存的是字符串常量,值不能被修改,每次更新都会重新开辟空间,创建对象、重新指向,效率较低。所以提供了StringBuilder和StringBuffer来增强String的功能。privatefinalcharvalue[]常用方法 equalsIgnoreCase()//忽略大小写判断是否相等indexOf()//字符在字符串中第......