2016-11-13 21 views
0

我的日期格式爲yyyyMMddHHmm,從此dateformat我需要提取年,月,日,並將1259添加爲HHmm以創建一個新日期, 我正在使用joda日期時間。將零填充爲單個數字以分格式製作

String date = (Integer.toString(orderDate.getYear()) + Integer.toString(orderDate.getMonthOfYear()) + Integer.toString(orderDate.getDayOfMonth()) + "1259"); 

orderDate = DateTimeFormat.forPattern(DATE_FORMAT).withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(date1TimeZone))).parseDateTime(String.valueOf(date)); 

但是,如果在orderDate恰好是201611051212 我得到的結果是20161151259即一個月的值是5,我想爲05.是否有使時鐘輸入任何格式說明?

回答

2

來自Joda docs:「模式字母的數量決定了格式」。

解決的辦法是使用Joda metohds來修改日期,因此您不需要發明用於操縱字符串的東西。

// your initial date 
    DateTime initialDate = DateTimeFormat.forPattern("yyyyMMddHHmm").parseDateTime("201611051212"); 

    // the operation you're trying emulate by adding a string, better to use specialized method 
    DateTime resultingDate = initialDate.withTime(12, 59, 0, 0); 

    // resulting string representation matches to what you specified as an expected result 
    String result = DateTimeFormat.forPattern("yyyyMMddHHmm").print(resultingDate); 
    Assert.assertEquals("201611051259", result);