how to convert string into time format and add two hours

后端 未结 9 1015
轻奢々
轻奢々 2020-12-13 05:04

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.

相关标签:
9条回答
  • 2020-12-13 05:11
    //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);
    
    0 讨论(0)
  • 2020-12-13 05:12

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

    0 讨论(0)
  • 2020-12-13 05:21

    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
    0 讨论(0)
  • 2020-12-13 05:23

    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.

    0 讨论(0)
  • 2020-12-13 05:25

    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?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    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.

    0 讨论(0)
  • 2020-12-13 05:28

    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())); 
    
    0 讨论(0)
提交回复
热议问题