首页 > 代码库 > 计算时间偏移量小工具

计算时间偏移量小工具

1.用Calendar计算偏移时间

2.calendar.add()方法可以自动偏移

public static void main(String[] args) throws ScriptException, ParseException {

        System.out.println(getNewTradeTime(‘y‘,"20160305010203",3));

    }
    public static String getNewTradeTime(char signal,String tradeTime,int offset) throws ParseException {
        int translate;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        Date now = sdf.parse(tradeTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        char c = String.valueOf(signal).toUpperCase().charAt(0);
        switch (c){
            case ‘C‘:
                return tradeTime;
            case ‘Y‘:
                translate = Calendar.YEAR; break;
            case ‘M‘:
                translate = Calendar.MONTH; break;
            case ‘D‘:
                translate = Calendar.DAY_OF_MONTH; break;
            case ‘H‘:
                translate = Calendar.HOUR; break;
            case ‘I‘:
                translate = Calendar.MINUTE; break;
            case ‘S‘:
                translate = Calendar.SECOND; break;
            case ‘L‘:
                translate = Calendar.MONTH; break;
            default:
                return "";
        }
        calendar.add(translate, offset);
        tradeTime = sdf.format(calendar.getTime());
        return tradeTime;
    }

往后三年,输出:

20190305010203

 

计算时间偏移量小工具