我有一个与日期转换/格式相关的问题。格式化日期和时间
我有一个日期,比如说,工作日期与一个值,例如:2011-11-27 00:00:00 从输入文本框,我收到一个时间值(作为字符串)的形式“HH:毫米:ss“,例如:”06:00:00“
我的任务是创建一个新的日期,比如newWorkDate,它具有与workDate相同的年份,月份,日期和时间作为文本框输入值。
所以在这种情况下,newWorkDate应该等于2011-11-27 06:00:00。 你能帮我弄清楚如何使用Java来实现这一点吗?
这是我到目前为止有:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
//Text box input is converted to Date format -what will be the default year,month and date set here?
Date textBoxTime = df.parse(minorMandatoryShiftStartTimeStr);
Date workDate = getWorkDate();
int year = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(0, 4));
int month = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(4, 6));
int date = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(6, 8));
Date newWorkDate = DateHelper.createDate(year, month, day);
//not sure how to set the textBox time to this newWorkDate.
[UPDATE]: Thx for the help,guys!Here is the updated code based on all your suggestions..Hopefully this will work.:)
String[] split = textBoxTime.split(":");
int hour = 0;
if (!split[0].isEmpty)){
hour = Integer.parseInt(split[0]);}
int minute = 0;
if (!split[1].isEmpty()){
minute = Integer.parseInt(split[1]);}
int second = 0;
if (!split[2].isEmpty()){
second = Integer.parseInt(split[2]);}
Calendar cal=Calendar.getInstance();
cal.setTime(workDate);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
Date newWorkDate = cal.getTime();
我已经提出了包括问题本身在内的所有答案,因为它们似乎都是正确的,值得一提的是独一无二的。 – Lion 2012-01-02 06:34:38
查看我上面的更新代码.Thx – user656523 2012-01-02 06:37:08