Hi, I have the following requirement in the porject. I have a input field by name startdate and user enters in the format YYYY-MM-DD HH:MM:SS. I need to add two hours for the user input in the startdate field. how can i do it.
Thanks in advance
Hi, I have the following requirement in the porject. I have a input field by name startdate and user enters in the format YYYY-MM-DD HH:MM:SS. I need to add two hours for the user input in the startdate field. how can i do it.
Thanks in advance
You can use SimpleDateFormat to convert the String to Date. And after that you have two options,
get the time in millisecond from that date object, and add two hours like, (2 * 60 * 60 * 1000)
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// replace with your start date string
Date d = df.parse("2008-04-16 00:05:05");
Calendar gc = new GregorianCalendar();
gc.setTime(d);
gc.add(Calendar.HOUR, 2);
Date d2 = gc.getTime();
Or,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// replace with your start date string
Date d = df.parse("2008-04-16 00:05:05");
Long time = d.getTime();
time +=(2*60*60*1000);
Date d2 = new Date(time);
Have a look to these tutorials.
Use the SimpleDateFormat
class parse()
method. This method will return a Date
object. You can then create a Calendar
object for this Date
and add 2 hours to it.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formatter.parse(theDateToParse);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 2);
cal.getTime(); // This will give you the time you want.
Being a fan of the Joda Time library, here's how you can do it that way using a Joda DateTime
:
import org.joda.time.format.*;
import org.joda.time.*;
...
String dateString = "2009-04-17 10:41:33";
// parse the string
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = formatter.parseDateTime(dateString);
// add two hours
dateTime = dateTime.plusHours(2); // easier than mucking about with Calendar and constants
System.out.println(dateTime);
If you still need to use java.util.Date
objects before/after this conversion, the Joda DateTime
API provides some easy toDate()
and toCalendar()
methods for easy translation.
The Joda API provides so much more in the way of convenience over the Java Date/Calendar API.