JAVA修改String格式的日期

JAVA modify date of String format

//大家好,

所以,我有方法

public void init() {
        list = taskManager.getList();
        list.sort((object1, object2) -> ((String) object2.getProperties().get("bpm_startDate"))
        .compareTo((String) object1.getProperties().get("bpm_startDate")));
 }

此方法按日期对我的列表进行排序,列表由 REST 服务填充,因此日期采用字符串格式。

<p:column headerText="#{msg.date}" >
    <h:outputText value="#{task.properties.bpm_startDate.substring(0,16).replace('T','  ')}">
    </h:outputText>
</p:column>

这就是我 "cut-off" 日期的所有冗余部分,然后再显示给用户的方式。

问题是,如何将日期加 3 小时?

您可以像这样使用 SimpleDateFormat 将字符串日期转换为日期

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(dateInString);

用于添加 Hours(时间) 检查日历 class。它有 add 方法(和其他一些方法)来允许时间操作。像这样的东西应该有用。

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
cal.getTime(); // returns new date object, one hour in the future

我强烈建议您查看 Joda-Time 库。 http://www.joda.org/joda-time/

由于我不知道您原始日期的存储格式,因此我无法提供您想要的确切代码,但您需要查看:

您可以使用 java.util.Calendar 和 DateFormat

//Parse String for Date
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); 
Date myDate = format.parse(stringDate);

//Use Calendar to add 3 hours
Calendar c = Calendar.getInstance();
c.setTime(myDate);
c.add(Calendar.HOUR_OF_DAY, 3);

//Retransform date to String
String newDate= format.format(c.getTime());

记得在 official documentation

之后用您的实际格式替换 "yyyy/MM/dd"