I have the following requirement in the project.
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
Use new Date() along with setHours() and getHours() to add time.
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
String time1="20:15:30"; String time2="13:50:35"; SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); timeFormat. setTimeZone(TimeZone. getTimeZone("UTC")); Date date1 = timeFormat. parse(time1); Date date2 = timeFormat.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With