2016-11-13 62 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);