我有一个与转换/日期格式相关的问题。
我有一个日期,比如说,workDate有一个值,例如:2011-11-27 00:00:00 从输入文本框中,我收到“HH:mm:ss”形式的时间值(如String),例如:“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();
答案 0 :(得分:2)
一些提示:
Calendar
对象处理日期。您可以从Calendar
设置Date
,这样您创建日期textBoxTime
和workDate
的方式就可以了。workDate
类上的setXXX方法(textBoxTime
一个Calendar
)workDate
设置Calendar
的值
SimpleDateFormat
进行格式化和解析。用它来产生所需的输出。你应该能够做到这一点,没有字符串解析和几行代码。
答案 1 :(得分:1)
由于您已经拥有工作日期,所以您只需将时间框转换为秒并将其添加到日期对象中。
将日历用于日期算术。
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, hour);
cal.add(Calendar.MINUTE, minute);
cal.add(Calendar.SECOND, second);
Date desiredDate = cal.getTime();
答案 2 :(得分:1)
您可能需要以下代码。
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) {
try {
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date workDate = simpleDateFormat1.parse("2011-11-27");
Calendar workCalendar= Calendar.getInstance();
workCalendar.setTime(workDate);
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");
Calendar time = Calendar.getInstance();
time.setTime(simpleDateFormat2.parse("06:00:00"));
workCalendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
workCalendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
workCalendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
Date newWorkDate = workCalendar.getTime();
SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
System.out.println(simpleDateFormat3.format(newWorkDate));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
希望这会对你有所帮助。