在jsp中结合日期和时间

时间:2014-01-02 05:30:21

标签: java javascript jsp date datetime

var dateString=$('#strtime').val();//starttime retrieved from db,(type is Time in the database)
var dateString2=$('#endtime').val();//endtime retrieved from db,(type is Time in the database)
var dateString1=$('#date').val();//date retrieved from db,(type is date in the database)
var d1 = new Date(dateString1+" "+dateString);//combine date and starttime retireved from the database.
var d5= new Date(dateString1+" "+dateString2);//combine date and endtime retireved from the database.

我想知道上面javascript的Java等价物

我试过这个

Date d1 = new Date(dateString1.getTime()+dateString.getTime());
System.out.println("d1="+d1);

// OUTPUT

d1=2013-12-27

这只输出日期,而不是时间

实际输出应为

d1=2013-12-27 14:30:00

2 个答案:

答案 0 :(得分:1)

尝试以下

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("d1 = " + dateFormat.format(d1));

修改

尝试以下方法

private Date combineDateTime(Date date, Date time)
{
    Calendar calendarA = Calendar.getInstance();
    calendarA.setTime(date);
    Calendar calendarB = Calendar.getInstance();
    calendarB.setTime(time);

    calendarA.set(Calendar.HOUR_OF_DAY, calendarB.get(Calendar.HOUR_OF_DAY));
    calendarA.set(Calendar.MINUTE, calendarB.get(Calendar.MINUTE));
    calendarA.set(Calendar.SECOND, calendarB.get(Calendar.SECOND));
    calendarA.set(Calendar.MILLISECOND, calendarB.get(Calendar.MILLISECOND));

    Date result = calendarA.getTime();
    return result;
}

答案 1 :(得分:1)

Java等价物

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

如果您需要特定时区,可以设置时区

SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
ft.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println("Date: " + ft.format(d1));

目前的日期

Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
System.out.println("Current Date: " + ft.format(dNow));
/// prints Current Date: 2014-01-02 13:38:02

System.out.println("Date: " + ft.format(date));