首页 > 其他分享 >获取2个时间之间的所有年月,年月日,年月日时。

获取2个时间之间的所有年月,年月日,年月日时。

时间:2023-08-16 21:32:13浏览次数:29  
标签:Stream 获取 List start iterate LocalDateTime 年月日时 年月日 logger



LocalDateTimeUtils.java


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class LocalDateTimeUtils {
    private static final Logger logger = LoggerFactory.getLogger(LocalDateTimeUtils.class);
    //年月
    public static final String YEAR_MONTH = "yyyyMM";

    //年月日
    public static final String YEAR_MONTH_DAY = "yyyyMMdd";

    //年月日时
    public static final String YEAR_MONTH_HOURS = "yyyyMMddHH";

    public static List<String> getMonthsBetween(LocalDateTime start, LocalDateTime end, String timeFormat) {
        return Stream.iterate(start, d -> d.plusMonths(1))
                .limit(ChronoUnit.MONTHS.between(start, end) + 1)
                .map(localDateTime -> {
                    return localDateTime.format(DateTimeFormatter.ofPattern(timeFormat));
                })
                .collect(Collectors.toList());
    }

    public static List<String> getDaysBetween(LocalDateTime start, LocalDateTime end, String timeFormat) {
        return Stream.iterate(start, d -> d.plusDays(1))
                .limit(ChronoUnit.DAYS.between(start, end) + 1)
                .map(localDateTime -> {
                    return localDateTime.format(DateTimeFormatter.ofPattern(timeFormat));
                })
                .collect(Collectors.toList());
    }

    public static List<String> getHoursBetween(LocalDateTime start, LocalDateTime end, String timeFormat) {
        return Stream.iterate(start, d -> d.plusHours(1))
                .limit(ChronoUnit.HOURS.between(start, end) + 1)
                .map(localDateTime -> {
                    return localDateTime.format(DateTimeFormatter.ofPattern(timeFormat));
                })
                .collect(Collectors.toList());
    }


    public static void main(String[] args) {
        LocalDateTime b = LocalDateTime.of(2023,5,1, 13, 48,51);
        LocalDateTime e = LocalDateTime.of(2023,8,15, 16, 28,11);
        List<String> list1 = getMonthsBetween(b, e, YEAR_MONTH);
        logger.info(list1.toString());
        List<String> list2 = getDaysBetween(b, e, YEAR_MONTH_DAY);
        logger.info(list2.toString());
        List<String> list3 = getMonthsBetween(b, e, YEAR_MONTH_HOURS);
        logger.info(list3.toString());

        logger.info("---------l2--------------");
        List<LocalDateTime> l2 = Stream.iterate(b, p -> p.plusHours(1)).limit( ChronoUnit.HOURS.between(b, e) + 1 ).collect(Collectors.toList());
        for (LocalDateTime t: l2) {
            logger.info(t.toString());
        }

        logger.info("---------l0--------------");
        List<LocalDateTime> l0 = Stream.iterate(b, p -> p.plusDays(1)).limit( ChronoUnit.DAYS.between(b, e) + 1 ).collect(Collectors.toList());
        for (LocalDateTime t: l0) {
            logger.info(t.toString());
        }

        logger.info("---------l1--------------");
        List<LocalDateTime> l1 = Stream.iterate(b, p -> p.plusMonths(1)).limit( ChronoUnit.MONTHS.between(b, e) + 1 ).collect(Collectors.toList());
        for (LocalDateTime t: l1) {
            logger.info(t.toString());
        }



    }

}

输出:

获取2个时间之间的所有年月,年月日,年月日时。_java

主要使用的是先用ChronoUnit工具,

ChronoUnit.MONTHS.between(start,end)

先算出start到end有多少个指定单位的数量,简单就是说有多少个月,有多少天,有多少小时等;然后利用Stream.iterate来生成对应的集合迭代器

Stream.iterate(initial value, next value)  Stream.iterate(0, n -> n + 1).limit(10);
//这样会生成0,1,2,....9;

java9对Stream.iterate进行了增强。新增了第二个参数为退出条件。

Stream.iterate(1, n -> n < 20 , n -> n * 2)   .forEach(x -> System.out.println(x));
//1,2,4,8,16

然后Stream.iterate的start时间,然后进行每月,每天,每小时为单位进新新增得到集合。

上面的工具类再次使用了map对每个成员进行了格式化,然后形成新的列表。

标签:Stream,获取,List,start,iterate,LocalDateTime,年月日时,年月日,logger
From: https://blog.51cto.com/lenglingx/7113655

相关文章

  • 获取鼠标相对于浏览器窗口坐标
    <!DOCTYPEhtml><html><head><style>div{position:fixed;top:10px;left:10px;padding:10px;background-color:#f1f1f1;border:1pxsolid#cc......
  • [Multimedia][ffmpeg] 音频音量获取
    ffmpeg-i~/media/test.mp4-filter_complexvolumedetect-c:vcopy-fnull/dev/null...[Parsed_volumedetect_0@0x7f83a481c000]n_samples:23887872[Parsed_volumedetect_0@0x7f83a481c000]mean_volume:-16.7dB[Parsed_volumedetect_0@0x7f83a481c000]......
  • 获取Web.config配置节
    staticstringGetAppSetting(stringkey){varappSetting=ConfigurationManager.AppSettings[key];if(string.IsNullOrEmpty(appSetting)){returnstring.Format("未配置节点"+key);......
  • pageinfo-只能读取当前条数不能获取总条数
    pageInfo的total属性是当前页记录数,如何配置使total设置成总记录数原 PageHelper.startPage(page,pageSize);LambdaQueryWrapper<Credit>queryWrapper=newQueryWrapper<Credit>().lambda().eq(Credit::getUserId,dto.getUid());......
  • ABAP HR 获取薪酬
    1DATA:2l_indexLIKEsy-tabix,3lt_rgdirTYPETABLEOFpc260,"payrollcluster4lw_rgdirLIKELINEOFlt_rgdir,5lt_rgdir_aTYPETABLEOFpc260,"payrollcluster6lw_rgdi......
  • x64ShellCode-通过PEB获取模块地址.
    以x64dbg.exe调试x64dbg.exe为例.汇编代码为如下.movrax,qwordptrgs:[0x0000000000000060]movrax,qwordptrds:[rax+0x10]二进制硬编码如下"\x65\x48\x8B\x04\x25\x60\x00\x00\x00\x48\x8B\x40\x10\x90\x90"结果如下:......
  • 获取Windows窗口
    抄自:  https://blog.csdn.net/freedom2211/article/details/131288406windowIterator.hclassCWindowIterator{private:staticchar*wchar2char(constwchar_t*wchar);staticBOOLCALLBACKEnumWindowsProc(HWNDwindow,LPARAMlParam);public:usingEnumC......
  • uniapp,微信小程序获取用户手机号
    1.获取手机号的按钮<buttonv-if="!mobile"class="btns"style="margin-top:-100rpx;"open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权手机号码</button>2.获取手机号的函数getPhoneNumber()getPhoneNu......
  • vue 获取设备指纹
    import Fingerprint2 from 'fingerprintjs2'//async异步请求asyncgetFingerprint(){returnnewPromise((resolve,reject)=>{Fingerprint2.getV18({},(result,components)=>{resolve(result)})})}......
  • 8-15| _ctypes.COMError: (-2147352567, '发生意外。', ('无法获取 Document 对象', '
    此错误是一个COM错误,它与试图从Python通过`pyautocad`与AutoCAD通信时出现的问题有关。错误信息"无法获取Document对象"指示了问题的本质,即Python无法访问AutoCAD的当前文档。这里有一些建议来解决这个问题:1.**确保AutoCAD已经运行**:在尝试从Python访问Aut......