user defined datetime input in java [duplicate]












-3
















This question already has an answer here:




  • How to find the duration of difference between two dates in java?

    14 answers




i wanted to take an input of date and time in the below format and need to calculate the time difference between two, can anyone suggest how to take below string as input and calculate the time difference.



user defined datetime input in java



String startTime= "11/27/2018+09:00:00";
String endTime= "11/28/2018+13:00:00";


The + is a separator (not a sign as in plus or minus).










share|improve this question















marked as duplicate by Ole V.V. java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 27 '18 at 6:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    DateTimeFormatter and Duration from the java.time API

    – MadProgrammer
    Nov 27 '18 at 3:23






  • 1





    search for 1) java input string from console 2) java parse string to date 3) java difference between LocalDate(s)

    – Kartik
    Nov 27 '18 at 3:24











  • @Roopesh Have you tried anything from yourself?

    – Abhinav
    Nov 27 '18 at 4:45











  • What is the expected result in this case? Sorry, it’s not immediately clear since I don’t see any time of day in your input. 20 hours? 24 hours? 1 day? Welcome to Stack Overflow.

    – Ole V.V.
    Nov 27 '18 at 5:15








  • 1





    @Ole thanks for correcting me actually the format is “MM/DD/YYYY+09:00:00” + is string separater.

    – Roopesh
    Nov 27 '18 at 6:23
















-3
















This question already has an answer here:




  • How to find the duration of difference between two dates in java?

    14 answers




i wanted to take an input of date and time in the below format and need to calculate the time difference between two, can anyone suggest how to take below string as input and calculate the time difference.



user defined datetime input in java



String startTime= "11/27/2018+09:00:00";
String endTime= "11/28/2018+13:00:00";


The + is a separator (not a sign as in plus or minus).










share|improve this question















marked as duplicate by Ole V.V. java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 27 '18 at 6:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    DateTimeFormatter and Duration from the java.time API

    – MadProgrammer
    Nov 27 '18 at 3:23






  • 1





    search for 1) java input string from console 2) java parse string to date 3) java difference between LocalDate(s)

    – Kartik
    Nov 27 '18 at 3:24











  • @Roopesh Have you tried anything from yourself?

    – Abhinav
    Nov 27 '18 at 4:45











  • What is the expected result in this case? Sorry, it’s not immediately clear since I don’t see any time of day in your input. 20 hours? 24 hours? 1 day? Welcome to Stack Overflow.

    – Ole V.V.
    Nov 27 '18 at 5:15








  • 1





    @Ole thanks for correcting me actually the format is “MM/DD/YYYY+09:00:00” + is string separater.

    – Roopesh
    Nov 27 '18 at 6:23














-3












-3








-3


0







This question already has an answer here:




  • How to find the duration of difference between two dates in java?

    14 answers




i wanted to take an input of date and time in the below format and need to calculate the time difference between two, can anyone suggest how to take below string as input and calculate the time difference.



user defined datetime input in java



String startTime= "11/27/2018+09:00:00";
String endTime= "11/28/2018+13:00:00";


The + is a separator (not a sign as in plus or minus).










share|improve this question

















This question already has an answer here:




  • How to find the duration of difference between two dates in java?

    14 answers




i wanted to take an input of date and time in the below format and need to calculate the time difference between two, can anyone suggest how to take below string as input and calculate the time difference.



user defined datetime input in java



String startTime= "11/27/2018+09:00:00";
String endTime= "11/28/2018+13:00:00";


The + is a separator (not a sign as in plus or minus).





This question already has an answer here:




  • How to find the duration of difference between two dates in java?

    14 answers








java datetime calendar date-difference






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 27 '18 at 6:48









Ole V.V.

29.4k63653




29.4k63653










asked Nov 27 '18 at 3:22









RoopeshRoopesh

12




12




marked as duplicate by Ole V.V. java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 27 '18 at 6:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Ole V.V. java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 27 '18 at 6:46


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 1





    DateTimeFormatter and Duration from the java.time API

    – MadProgrammer
    Nov 27 '18 at 3:23






  • 1





    search for 1) java input string from console 2) java parse string to date 3) java difference between LocalDate(s)

    – Kartik
    Nov 27 '18 at 3:24











  • @Roopesh Have you tried anything from yourself?

    – Abhinav
    Nov 27 '18 at 4:45











  • What is the expected result in this case? Sorry, it’s not immediately clear since I don’t see any time of day in your input. 20 hours? 24 hours? 1 day? Welcome to Stack Overflow.

    – Ole V.V.
    Nov 27 '18 at 5:15








  • 1





    @Ole thanks for correcting me actually the format is “MM/DD/YYYY+09:00:00” + is string separater.

    – Roopesh
    Nov 27 '18 at 6:23














  • 1





    DateTimeFormatter and Duration from the java.time API

    – MadProgrammer
    Nov 27 '18 at 3:23






  • 1





    search for 1) java input string from console 2) java parse string to date 3) java difference between LocalDate(s)

    – Kartik
    Nov 27 '18 at 3:24











  • @Roopesh Have you tried anything from yourself?

    – Abhinav
    Nov 27 '18 at 4:45











  • What is the expected result in this case? Sorry, it’s not immediately clear since I don’t see any time of day in your input. 20 hours? 24 hours? 1 day? Welcome to Stack Overflow.

    – Ole V.V.
    Nov 27 '18 at 5:15








  • 1





    @Ole thanks for correcting me actually the format is “MM/DD/YYYY+09:00:00” + is string separater.

    – Roopesh
    Nov 27 '18 at 6:23








1




1





DateTimeFormatter and Duration from the java.time API

– MadProgrammer
Nov 27 '18 at 3:23





DateTimeFormatter and Duration from the java.time API

– MadProgrammer
Nov 27 '18 at 3:23




1




1





search for 1) java input string from console 2) java parse string to date 3) java difference between LocalDate(s)

– Kartik
Nov 27 '18 at 3:24





search for 1) java input string from console 2) java parse string to date 3) java difference between LocalDate(s)

– Kartik
Nov 27 '18 at 3:24













@Roopesh Have you tried anything from yourself?

– Abhinav
Nov 27 '18 at 4:45





@Roopesh Have you tried anything from yourself?

– Abhinav
Nov 27 '18 at 4:45













What is the expected result in this case? Sorry, it’s not immediately clear since I don’t see any time of day in your input. 20 hours? 24 hours? 1 day? Welcome to Stack Overflow.

– Ole V.V.
Nov 27 '18 at 5:15







What is the expected result in this case? Sorry, it’s not immediately clear since I don’t see any time of day in your input. 20 hours? 24 hours? 1 day? Welcome to Stack Overflow.

– Ole V.V.
Nov 27 '18 at 5:15






1




1





@Ole thanks for correcting me actually the format is “MM/DD/YYYY+09:00:00” + is string separater.

– Roopesh
Nov 27 '18 at 6:23





@Ole thanks for correcting me actually the format is “MM/DD/YYYY+09:00:00” + is string separater.

– Roopesh
Nov 27 '18 at 6:23












2 Answers
2






active

oldest

votes


















1














Senseless input



String startTime= "11/27/2018+09:00";
String endTime= "11/28/2018+13:00";


These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.



For an offset to have meaning, you need a date and a time-of-day.



We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.



The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.



The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.



Guesswork



If correcting the source of this data is not feasible, then we can plod on with guesswork.



Extract the date, separate from offset.



String input = "11/27/2018+09:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );



localDate.toString(): 2018-11-27



zoneOffset.toString(): +09:00




OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );



2018-11-27T00:00+09:00




We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.



Duration d = Duration.between( odt , odtLater ) ; 




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.



You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



Where to obtain the java.time classes?





  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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


    • Most 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 (<26), 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.






share|improve this answer

































    0














    In java 8 there is:
    LocalDateTime: use this if you need to deal with date and time.
    LocalDate: use this if you need to deal with date only.
    ZonedDateTime: use this if you need to deal with date time with time zone.
    OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)



    Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).



    However, I think you can solved it like this:



    Create a method that convert your date string into OffsetDateTime like this:



    private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
    {
    //TODO: assert that dateWithTimeOffset is valid
    String date = dateWithTimeOffset.substring (0, 10);
    String timeOffset = dateWithTimeOffset.substring (10, 13);

    //define your date pattern
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");

    return LocalDate.parse (date, formatter) // create LocalDate
    .atStartOfDay () // convert it to LocalDateTime with time 00:00:00
    .atOffset (ZoneOffset.of(timeOffset)); // apply the offset
    }


    Then you can simple create your OffsetDateTime like this:



    OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");  
    OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");


    You can create duration using OffsetDateTime like this:



    Duration duration = Duration.between (startTime, endTime);


    Duration have everything you need related with time duration, for example:



    duration.toHours () // will give you the hour duration





    share|improve this answer


























    • @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement.

      – Roopesh
      Nov 27 '18 at 5:50











    • @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out OffsetDateTime I am not aware of this before.

      – efmalik
      Nov 27 '18 at 8:18




















    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Senseless input



    String startTime= "11/27/2018+09:00";
    String endTime= "11/28/2018+13:00";


    These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.



    For an offset to have meaning, you need a date and a time-of-day.



    We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.



    The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.



    The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.



    Guesswork



    If correcting the source of this data is not feasible, then we can plod on with guesswork.



    Extract the date, separate from offset.



    String input = "11/27/2018+09:00";
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
    LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
    ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );



    localDate.toString(): 2018-11-27



    zoneOffset.toString(): +09:00




    OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );



    2018-11-27T00:00+09:00




    We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.



    Duration d = Duration.between( odt , odtLater ) ; 




    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.



    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



    Where to obtain the java.time classes?





    • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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


      • Most 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 (<26), 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.






    share|improve this answer






























      1














      Senseless input



      String startTime= "11/27/2018+09:00";
      String endTime= "11/28/2018+13:00";


      These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.



      For an offset to have meaning, you need a date and a time-of-day.



      We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.



      The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.



      The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.



      Guesswork



      If correcting the source of this data is not feasible, then we can plod on with guesswork.



      Extract the date, separate from offset.



      String input = "11/27/2018+09:00";
      DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
      LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
      ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );



      localDate.toString(): 2018-11-27



      zoneOffset.toString(): +09:00




      OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );



      2018-11-27T00:00+09:00




      We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.



      Duration d = Duration.between( odt , odtLater ) ; 




      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.



      You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



      Where to obtain the java.time classes?





      • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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


        • Most 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 (<26), 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.






      share|improve this answer




























        1












        1








        1







        Senseless input



        String startTime= "11/27/2018+09:00";
        String endTime= "11/28/2018+13:00";


        These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.



        For an offset to have meaning, you need a date and a time-of-day.



        We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.



        The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.



        The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.



        Guesswork



        If correcting the source of this data is not feasible, then we can plod on with guesswork.



        Extract the date, separate from offset.



        String input = "11/27/2018+09:00";
        DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
        LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
        ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );



        localDate.toString(): 2018-11-27



        zoneOffset.toString(): +09:00




        OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );



        2018-11-27T00:00+09:00




        We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.



        Duration d = Duration.between( odt , odtLater ) ; 




        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.



        You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



        Where to obtain the java.time classes?





        • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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


          • Most 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 (<26), 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.






        share|improve this answer















        Senseless input



        String startTime= "11/27/2018+09:00";
        String endTime= "11/28/2018+13:00";


        These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.



        For an offset to have meaning, you need a date and a time-of-day.



        We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.



        The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.



        The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.



        Guesswork



        If correcting the source of this data is not feasible, then we can plod on with guesswork.



        Extract the date, separate from offset.



        String input = "11/27/2018+09:00";
        DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
        LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
        ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );



        localDate.toString(): 2018-11-27



        zoneOffset.toString(): +09:00




        OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );



        2018-11-27T00:00+09:00




        We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.



        Duration d = Duration.between( odt , odtLater ) ; 




        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.



        You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



        Where to obtain the java.time classes?





        • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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


          • Most 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 (<26), 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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 27 '18 at 16:54

























        answered Nov 27 '18 at 6:13









        Basil BourqueBasil Bourque

        112k28385545




        112k28385545

























            0














            In java 8 there is:
            LocalDateTime: use this if you need to deal with date and time.
            LocalDate: use this if you need to deal with date only.
            ZonedDateTime: use this if you need to deal with date time with time zone.
            OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)



            Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).



            However, I think you can solved it like this:



            Create a method that convert your date string into OffsetDateTime like this:



            private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
            {
            //TODO: assert that dateWithTimeOffset is valid
            String date = dateWithTimeOffset.substring (0, 10);
            String timeOffset = dateWithTimeOffset.substring (10, 13);

            //define your date pattern
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");

            return LocalDate.parse (date, formatter) // create LocalDate
            .atStartOfDay () // convert it to LocalDateTime with time 00:00:00
            .atOffset (ZoneOffset.of(timeOffset)); // apply the offset
            }


            Then you can simple create your OffsetDateTime like this:



            OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");  
            OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");


            You can create duration using OffsetDateTime like this:



            Duration duration = Duration.between (startTime, endTime);


            Duration have everything you need related with time duration, for example:



            duration.toHours () // will give you the hour duration





            share|improve this answer


























            • @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement.

              – Roopesh
              Nov 27 '18 at 5:50











            • @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out OffsetDateTime I am not aware of this before.

              – efmalik
              Nov 27 '18 at 8:18


















            0














            In java 8 there is:
            LocalDateTime: use this if you need to deal with date and time.
            LocalDate: use this if you need to deal with date only.
            ZonedDateTime: use this if you need to deal with date time with time zone.
            OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)



            Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).



            However, I think you can solved it like this:



            Create a method that convert your date string into OffsetDateTime like this:



            private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
            {
            //TODO: assert that dateWithTimeOffset is valid
            String date = dateWithTimeOffset.substring (0, 10);
            String timeOffset = dateWithTimeOffset.substring (10, 13);

            //define your date pattern
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");

            return LocalDate.parse (date, formatter) // create LocalDate
            .atStartOfDay () // convert it to LocalDateTime with time 00:00:00
            .atOffset (ZoneOffset.of(timeOffset)); // apply the offset
            }


            Then you can simple create your OffsetDateTime like this:



            OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");  
            OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");


            You can create duration using OffsetDateTime like this:



            Duration duration = Duration.between (startTime, endTime);


            Duration have everything you need related with time duration, for example:



            duration.toHours () // will give you the hour duration





            share|improve this answer


























            • @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement.

              – Roopesh
              Nov 27 '18 at 5:50











            • @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out OffsetDateTime I am not aware of this before.

              – efmalik
              Nov 27 '18 at 8:18
















            0












            0








            0







            In java 8 there is:
            LocalDateTime: use this if you need to deal with date and time.
            LocalDate: use this if you need to deal with date only.
            ZonedDateTime: use this if you need to deal with date time with time zone.
            OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)



            Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).



            However, I think you can solved it like this:



            Create a method that convert your date string into OffsetDateTime like this:



            private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
            {
            //TODO: assert that dateWithTimeOffset is valid
            String date = dateWithTimeOffset.substring (0, 10);
            String timeOffset = dateWithTimeOffset.substring (10, 13);

            //define your date pattern
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");

            return LocalDate.parse (date, formatter) // create LocalDate
            .atStartOfDay () // convert it to LocalDateTime with time 00:00:00
            .atOffset (ZoneOffset.of(timeOffset)); // apply the offset
            }


            Then you can simple create your OffsetDateTime like this:



            OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");  
            OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");


            You can create duration using OffsetDateTime like this:



            Duration duration = Duration.between (startTime, endTime);


            Duration have everything you need related with time duration, for example:



            duration.toHours () // will give you the hour duration





            share|improve this answer















            In java 8 there is:
            LocalDateTime: use this if you need to deal with date and time.
            LocalDate: use this if you need to deal with date only.
            ZonedDateTime: use this if you need to deal with date time with time zone.
            OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)



            Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).



            However, I think you can solved it like this:



            Create a method that convert your date string into OffsetDateTime like this:



            private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
            {
            //TODO: assert that dateWithTimeOffset is valid
            String date = dateWithTimeOffset.substring (0, 10);
            String timeOffset = dateWithTimeOffset.substring (10, 13);

            //define your date pattern
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");

            return LocalDate.parse (date, formatter) // create LocalDate
            .atStartOfDay () // convert it to LocalDateTime with time 00:00:00
            .atOffset (ZoneOffset.of(timeOffset)); // apply the offset
            }


            Then you can simple create your OffsetDateTime like this:



            OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");  
            OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");


            You can create duration using OffsetDateTime like this:



            Duration duration = Duration.between (startTime, endTime);


            Duration have everything you need related with time duration, for example:



            duration.toHours () // will give you the hour duration






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 27 '18 at 8:18

























            answered Nov 27 '18 at 5:35









            efmalikefmalik

            465




            465













            • @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement.

              – Roopesh
              Nov 27 '18 at 5:50











            • @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out OffsetDateTime I am not aware of this before.

              – efmalik
              Nov 27 '18 at 8:18





















            • @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement.

              – Roopesh
              Nov 27 '18 at 5:50











            • @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out OffsetDateTime I am not aware of this before.

              – efmalik
              Nov 27 '18 at 8:18



















            @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement.

            – Roopesh
            Nov 27 '18 at 5:50





            @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement.

            – Roopesh
            Nov 27 '18 at 5:50













            @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out OffsetDateTime I am not aware of this before.

            – efmalik
            Nov 27 '18 at 8:18







            @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out OffsetDateTime I am not aware of this before.

            – efmalik
            Nov 27 '18 at 8:18





            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks