常用工具(四) -- 时间工具类

时间工具类

import org.apache.commons.lang3.time.FastDateFormat
object DateUtils {
	
	/**
	 * 获取当前的日期,格式为:20190710
	 */
	def getTodayDate(): String = {
		// a. 获取当前日期
		val nowDate = new Date()
		// b. 转换日期格式
		FastDateFormat.getInstance("yyyy-MM-dd").format(nowDate)
	}
	
	/**
	 * 获取昨日的日期,格式为:20190710
	 */
	def getYesterdayDate(): String = {
		// a. 获取Calendar对象
		val calendar: Calendar = Calendar.getInstance()
		// b. 获取昨日日期
		calendar.add(Calendar.DATE, -1)
		// c. 转换日期格式
		FastDateFormat.getInstance("yyyy-MM-dd").format(calendar)
	}
	
	def main(args: Array[String]): Unit = {
		println(s"Today: ${getTodayDate()}")
		println(s"Yesterday: ${getYesterdayDate()}")
	}
	
}
import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TimeParseUtils {
    public static Date parse(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        Pattern pattern = Pattern.compile("\\d{10}");
        if (pattern.matcher(str).matches()) {
            return new Date(Integer.parseInt(str) * 1000L);
        }

        pattern = Pattern.compile("(\\d*)(\\w+)");
        if ("now".equals(str) || str.length() == 0) {
            return new Date();
        }
        if ("rtnow".equals(str) || "rt".equals(str)) {
            return null;
        }
        if (str.startsWith("@")) {//@d
            return parseStr(new Date(), str.substring(1));
        } else if (str.indexOf("@") != -1) {//-1d@d
            String[] arr = str.split("@");
            Date dt = parseStr(pattern, arr[0]);
            return parseStr(dt, arr[1]);
        } else if (str.startsWith("rt")) {//rt-1d
            return parseStr(pattern, str.substring(2));
        } else {//-1d
            return parseStr(pattern, str);
        }
    }


    public static Long parseLong(String str, Long defaultValue) {
        Date dt = parse(str);
        return dt != null ? dt.getTime() : defaultValue;
    }

    public static Long parseLong(String str) {
        Date dt = parse(str);
        return dt != null ? dt.getTime() : -1;
    }

    private static Date parseStr(Date date, String unit) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MILLISECOND, 0);
        switch (unit) {
            case "s":
                break;
            case "m":
                calendar.set(Calendar.SECOND, 0);
                break;
            case "h":
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                break;
            case "w1":
            case "w2":
            case "w3":
            case "w4":
            case "w5":
            case "w6":
            case "w7":
            case "d":
                if (unit.startsWith("w")) {
                    int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                    if (day_of_week == 0) {
                        day_of_week = 7;
                    }
                    calendar.add(Calendar.DATE, -day_of_week + Integer.parseInt(unit.substring(1)));
                }
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                break;
            case "mon":
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.DATE, 1);
                break;
            case "q":
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.DATE, 1);
                int month = calendar.get(calendar.MONTH) + 1;
                int q = month / 3;
                calendar.set(Calendar.MONTH, q * 3);
                break;
            case "y":
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.DATE, 1);
                calendar.set(Calendar.MONTH, 0);
                break;
            default:
                throw new RuntimeException("time not support " + unit);
        }
        return calendar.getTime();
    }

    private static Date parseStr(Pattern pattern, String str) {
        Matcher matcher = pattern.matcher(str);
        if (!matcher.find()) {
            throw new RuntimeException("time not support " + str);
        }
        int num = Integer.parseInt(matcher.group(1));
        String unit = matcher.group(2);

        num = str.startsWith("-") ? 0 - num : num;

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.MILLISECOND, 0);
        switch (unit) {
            case "s":
                calendar.add(Calendar.SECOND, num);
                break;
            case "m":
                calendar.add(Calendar.MINUTE, num);
                break;
            case "h":
                calendar.add(Calendar.HOUR_OF_DAY, num);
                break;
            case "d":
                calendar.add(Calendar.DATE, num);
                break;
            case "w":
                calendar.add(Calendar.DATE, num * 7);
                break;
            case "mon":
                calendar.add(Calendar.MONTH, num);
                break;
            case "q":
                calendar.add(Calendar.MONTH, num * 3);
                break;
            case "y":
                calendar.add(Calendar.YEAR, num);
                break;
            case "w1":
            case "w2":
            case "w3":
            case "w4":
            case "w5":
            case "w6":
            case "w7":
                calendar.add(Calendar.DAY_OF_WEEK, num);
                break;

            default:
                throw new RuntimeException("time not support " + str);
        }
        return calendar.getTime();
    }


}
import org.junit.Test;

import java.text.SimpleDateFormat;

public class TimeParseTest {
    static SimpleDateFormat standerTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Test
    public void parseStr() {
        parse("rt-10mon", null);
        parse("1587872004", null);
        parse("rtnow", null);
        parse("rt-15m", null);

        parse("@s", null);
        parse("@m", null);
        parse("@h", null);
        parse("@d", null);
        parse("@mon", null);
        parse("@q", null);
        parse("@y", null);

        parse("@w1", null);
        parse("@w2", null);
        parse("@w3", null);
        parse("@w4", null);
        parse("@w5", null);
        parse("@w6", null);
        parse("@w7", null);

        System.out.println("----------------");


        parse("@s", null);
        parse("-1s", null);
        parse("-1m", null);
        parse("-1h", null);
        parse("-1d", null);
        parse("-1w", null);
        parse("-1mon", null);
        parse("-2mon", null);
        parse("-1q", null);
        parse("-2q", null);
        parse("-1y", null);
        System.out.println("----------------");


        parse("@s", null);
        parse("1s", null);
        parse("1m", null);
        parse("1h", null);
        parse("1d", null);
        parse("1w", null);
        parse("1mon", null);
        parse("2mon", null);
        parse("1q", null);
        parse("2q", null);
        parse("1y", null);

        System.out.println("----------------");


        parse("@s", null);
        parse("-10m", null);
        parse("-4h@m", null);
        parse("@d", null);
        parse("-1d@d", null);
        parse("-2d@d", null);

        parse("@w1", null);
        parse("@w7", null);
        parse("-7d@w1", null);

        parse("@mon", null);
        parse("-1mon@mon", null);

        parse("@q", null);
        parse("-1q@q", null);

        parse("1q@q", null);
        parse("2q@q", null);

        parse("-1q@q", null);
        parse("-2q@q", null);

        parse("@y", null);
        parse("-1y@y", null);
    }

    private static void parse(String str, String expect) {
        Object obj = TimeParseUtils.parse(str);
        if (obj != null) {
            String output = standerTimeFormat.format(obj);

            if (expect != null) {
                System.out.println(str + " " + output + " " + expect + " => " + output.equals(expect));
            } else {
                System.out.println(str + "->" + output);
            }
        }
    }
}

commons-lang3.3.1.jar、Apache Commons包中的一个,包含了一些数据类型工具类,是java.lang.*的扩展。必须使用的jar包。为JRE5.0+的更好的版本所提供 Jar文件包含的类: META-INF/MANIFEST.MFMETA-INF/LICENSE.txtMETA-INF/NOTICE.txtorg.apache.commons.lang.ArrayUtils.class org.apache.commons.lang.BitField.class org.apache.commons.lang.BooleanUtils.class org.apache.commons.lang.CharEncoding.class org.apache.commons.lang.CharRange.class org.apache.commons.lang.CharSet.class org.apache.commons.lang.CharSetUtils.class org.apache.commons.lang.CharUtils.class org.apache.commons.lang.ClassUtils.class org.apache.commons.lang.Entities$ArrayEntityMap.class org.apache.commons.lang.Entities$BinaryEntityMap.class org.apache.commons.lang.Entities$EntityMap.class org.apache.commons.lang.Entities$HashEntityMap.class org.apache.commons.lang.Entities$LookupEntityMap.class org.apache.commons.lang.Entities$MapIntMap.class org.apache.commons.lang.Entities$PrimitiveEntityMap.class org.apache.commons.lang.Entities$TreeEntityMap.class org.apache.commons.lang.Entities.class org.apache.commons.lang.IllegalClassException.class org.apache.commons.lang.IncompleteArgumentException.class org.apache.commons.lang.IntHashMap$Entry.class org.apache.commons.lang.IntHashMap.class org.apache.commons.lang.LocaleUtils.class org.apache.commons.lang.NotImplementedException.class org.apache.commons.lang.NullArgumentException.class org.apache.commons.lang.NumberRange.class org.apache.commons.lang.NumberUtils.class org.apache.commons.lang.ObjectUtils$Null.class org.apache.commons.lang.ObjectUtils.class org.apache.commons.lang.RandomStringUtils.class org.apache.commons.lang.SerializationException.class org.apache.commons.lang.SerializationUtils.class org.apache.commons.lang.StringEscapeUtils.class org.apache.commons.lang.StringUtils.class org.apache.commons.lang.SystemUtils.class org.apache.commons.lang.UnhandledException.class org.apache.commons.lang.Validate.class org.apache.commons.lang.WordUtils.class org.apache.commons.lang.builder.CompareToBuilder.class org.apache.commons.lang.builder.EqualsBuilder.class org.apache.commons.lang.builder.HashCodeBuilder.class org.apache.commons.lang.builder.ReflectionToStringBuilder$1.class org.apache.commons.lang.builder.ReflectionToStringBuilder.class org.apache.commons.lang.builder.StandardToStringStyle.class org.apache.commons.lang.builder.ToStringBuilder.class org.apache.commons.lang.builder.ToStringStyle$DefaultToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$MultiLineToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$NoFieldNameToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$ShortPrefixToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$SimpleToStringStyle.class org.apache.commons.lang.builder.ToStringStyle.class org.apache.commons.lang.enum.Enum$Entry.class org.apache.commons.lang.enum.Enum.class org.apache.commons.lang.enum.EnumUtils.class org.apache.commons.lang.enum.ValuedEnum.class org.apache.commons.lang.enums.Enum$Entry.class org.apache.commons.lang.enums.Enum.class org.apache.commons.lang.enums.EnumUtils.class org.apache.commons.lang.enums.ValuedEnum.class org.apache.commons.lang.exception.ExceptionUtils.class org.apache.commons.lang.exception.Nestable.class org.apache.commons.lang.exception.NestableDelegate.class org.apache.commons.lang.exception.NestableError.class org.apache.commons.lang.exception.NestableException.class org.apache.commons.lang.exception.NestableRuntimeException.class org.apache.commons.lang.math.DoubleRange.class org.apache.commons.lang.math.FloatRange.class org.apache.commons.lang.math.Fraction.class org.apache.commons.lang.math.IntRange.class org.apache.commons.lang.math.JVMRandom.class org.apache.commons.lang.math.LongRange.class org.apache.commons.lang.math.NumberRange.class org.apache.commons.lang.math.NumberUtils.class org.apache.commons.lang.math.RandomUtils.class org.apache.commons.lang.math.Range.class org.apache.commons.lang.mutable.Mutable.class org.apache.commons.lang.mutable.MutableBoolean.class org.apache.commons.lang.mutable.MutableByte.class org.apache.commons.lang.mutable.MutableDouble.class org.apache.commons.lang.mutable.MutableFloat.class org.apache.commons.lang.mutable.MutableInt.class org.apache.commons.lang.mutable.MutableLong.class org.apache.commons.lang.mutable.MutableObject.class org.apache.commons.lang.mutable.MutableShort.class org.apache.commons.lang.text.CompositeFormat.class org.apache.commons.lang.text.StrBuilder$StrBuilderReader.class org.apache.commons.lang.text.StrBuilder$StrBuilderTokenizer.class org.apache.commons.lang.text.StrBuilder$StrBuilderWriter.class org.apache.commons.lang.text.StrBuilder.class org.apache.commons.lang.text.StrLookup$MapStrLookup.class org.apache.commons.lang.text.StrLookup.class org.apache.commons.lang.text.StrMatcher$CharMatcher.class org.apache.commons.lang.text.StrMatcher$CharSetMatcher.class org.apache.commons.lang.text.StrMatcher$NoMatcher.class org.apache.commons.lang.text.StrMatcher$StringMatcher.class org.apache.commons.lang.text.StrMatcher$TrimMatcher.class org.apache.commons.lang.text.StrMatcher.class org.apache.commons.lang.text.StrSubstitutor.class org.apache.commons.lang.text.StrTokenizer.class org.apache.commons.lang.time.DateFormatUtils.class org.apache.commons.lang.time.DateUtils$DateIterator.class org.apache.commons.lang.time.DateUtils.class org.apache.commons.lang.time.DurationFormatUtils$Token.class org.apache.commons.lang.time.DurationFormatUtils.class org.apache.commons.lang.time.FastDateFormat$CharacterLiteral.class org.apache.commons.lang.time.FastDateFormat$NumberRule.class org.apache.commons.lang.time.FastDateFormat$PaddedNumberField.class org.apache.commons.lang.time.FastDateFormat$Pair.class org.apache.commons.lang.time.FastDateFormat$Rule.class org.apache.commons.lang.time.FastDateFormat$StringLiteral.class org.apache.commons.lang.time.FastDateFormat$TextField.class org.apache.commons.lang.time.FastDateFormat$TimeZoneDisplayKey.class org.apache.commons.lang.time.FastDateFormat$TimeZoneNameRule.class org.apache.commons.lang.time.FastDateFormat$TimeZoneNumberRule.class org.apache.commons.lang.time.FastDateFormat$TwelveHourField.class org.apache.commons.lang.time.FastDateFormat$TwentyFourHourField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitMonthField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitNumberField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitYearField.class org.apache.commons.lang.time.FastDateFormat$UnpaddedMonthField.class org.apache.commons.lang.time.FastDateFormat$UnpaddedNumberField.class org.apache.commons.lang.time.FastDateFormat.class org.apache.commons.lang.time.StopWatch.class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值