Combining date and time in jsp

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.

I would like to know the Java equivalent of the above javascript

I Tried this

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

//OUTPUT

d1=2013-12-27

This outputs only the date,not the time

Actual output should have been

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

Upvotes: 0

Views: 1010

Answers (2)

Raunak Kathuria
Raunak Kathuria

Reputation: 3225

Java equivalent would be

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

If you want specific timezone you can set the timezone

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

For current date

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));

Upvotes: 1

sasankad
sasankad

Reputation: 3613

try following

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

EDIT

try following method

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;
}

Upvotes: 1

Related Questions