Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert string into time format and add two hours [duplicate]

Tags:

java

datetime

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

like image 565
user48094 Avatar asked Apr 17 '09 04:04

user48094


People also ask

How do you add time to a string?

Use new Date() along with setHours() and getHours() to add time.

How do I convert a string to a datetime?

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.

How do you add time to a string in Java?

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.


2 Answers

You can use SimpleDateFormat to convert the String to Date. And after that you have two options,

  • Make a Calendar object and and then use that to add two hours, or
  • 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.

  • SimpleDateFormat Tutorial
  • Calendar Tutorial
like image 143
Adeel Ansari Avatar answered Sep 23 '22 21:09

Adeel Ansari


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.

like image 20
Rob Hruska Avatar answered Sep 20 '22 21:09

Rob Hruska