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

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

This question is related to java datetime

The answer is


This example is a Sum for Date time and Time Zone(String Values)

String DateVal = "2015-03-26 12:00:00";
String TimeVal = "02:00:00";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

Date reslt = sdf.parse( DateVal );
Date timeZ = sdf2.parse( TimeVal );
//Increase Date Time
reslt.setHours( reslt.getHours() + timeZ.getHours());
reslt.setMinutes( reslt.getMinutes() + timeZ.getMinutes());
reslt.setSeconds( reslt.getSeconds() + timeZ.getSeconds());

System.printLn.out( sdf.format(reslt) );//Result(+2 Hours):  2015-03-26 14:00:00 

Thanks :)


tl;dr

LocalDateTime.parse( 
    "2018-01-23 01:23:45".replace( " " , "T" )  
).plusHours( 2 )

java.time

The modern approach uses the java.time classes added to Java 8, Java 9, and later.

user enters in the format YYYY-MM-DD HH:MM:SS

Parse that input string into a date-time object. Your format is close to complying with standard ISO 8601 format, used by default in the java.time classes for parsing/generating strings. To fully comply, replace the SPACE in the middle with a T.

String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45

Parse as a LocalDateTime given that your input lacks any indicator of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

add two hours

The java.time classes can do the math for you.

LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;

Time Zone

Be aware that a LocalDateTime does not represent a moment, a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. The “Local” part of the name means any locality or no locality, rather than any one particular locality. Just saying "noon on Jan 21st" could mean noon in Auckland, New Zealand which happens several hours earlier than noon in Paris France.

To define an actual moment, you must specify a zone or offset.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  // Define an actual moment, a point on the timeline by giving a context with time zone.

If you know the intended time zone for certain, apply it before adding the two hours. The LocalDateTime class assumes simple generic 24-hour days when doing the math. But in various time zones on various dates, days may be 23 or 25 hours long, or may be other lengths. So, for correct results in a zoned context, add the hours to your ZonedDateTime rather than LocalDateTime.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


//the parsed time zone offset:
DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String fromDateTimeObj = "2011-01-03T12:00:00.000-0800";
DateTime fromDatetime = dateFormat.withOffsetParsed().parseDateTime(fromDateTimeObj);

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.


Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.

class demo
{private int hour,min,sec;
    void input(int hour,int min,int sec)
    {this.hour=hour;
    this.min=min;
    this.sec=sec;

    }
    demo add(demo d2)//demo  because we are returning object
    {   demo obj=new demo();
    obj.hour=hour+d2.hour;
    obj.min=min+d2.min;
    obj.sec=sec+d2.sec;
    return obj;//Returning object and later on it gets allocated to demo d3                    
    }
    void display()
    {
        System.out.println(hour+":"+min+":"+sec);
    }
    public static  void main(String args[])
    {
        demo d1=new demo();
        demo d2=new demo();
        d1.input(2, 5, 10);
        d2.input(3, 3, 3);
        demo d3=d1.add(d2);//Note another object is created
        d3.display();


    }

}

Modified Time Addition Program

class demo {private int hour,min,sec; void input(int hour,int min,int sec) {this.hour=(hour>12&&hour<24)?(hour-12):hour; this.min=(min>60)?0:min; this.sec=(sec>60)?0:sec; } demo add(demo d2) { demo obj=new demo(); obj.hour=hour+d2.hour; obj.min=min+d2.min; obj.sec=sec+d2.sec; if(obj.sec>60) {obj.sec-=60; obj.min++; } if(obj.min>60) { obj.min-=60; obj.hour++; } return obj; } void display() { System.out.println(hour+":"+min+":"+sec); } public static void main(String args[]) { demo d1=new demo(); demo d2=new demo(); d1.input(12, 55, 55); d2.input(12, 7, 6); demo d3=d1.add(d2); d3.display(); } }

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.


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.

Try this one, I test it, working fine

Date date = null;
String str = "2012/07/25 12:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
date = formatter.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 2);
System.out.println(calendar.getTime());  // Output : Wed Jul 25 14:00:00 IST 2012

If you want to convert in your input type than add this code also

formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
str=formatter.format(calendar.getTime());
System.out.println(str);  // Output : 2012-07-25 14:00:00

This will give you the time you want (eg: 21:31 PM)

//Add 2 Hours to just TIME
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
Date date2 = formatter.parse("19:31:51 PM");
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal2.add(Calendar.HOUR_OF_DAY, 2);
SimpleDateFormat printTimeFormat = new SimpleDateFormat("HH:mm a");
System.out.println(printTimeFormat.format(cal2.getTime()));