How to choose Date/Time class in java8 among LocalDateTime, ZonedDateTime and other classes?












0















I want to convert pre Java8 like below.



DateFormat formatter = new SimpleDateFormat(timestampPattern, locale);
Date dt = formatter.parse(timestamp);
Date currentDateTime = getCurrentTime();


To Java 8 code to support more than 3 digits in milliseconds. I found ways to do that using the following simple code.



String parsedate="2016-03-16 01:14:21.6739";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
LocalDateTime newdate = LocalDateTime.parse(parsedate, dateTimeFormatter);


Problem with above code is that you have to know specific class before parsing it like if it contains only date in you have to use LocalDate and if only time LocalTime and if date + time + zone you have to use ZonedDateTime.



My problem is that I don't know timestampPattern or timestamp(Given in pre Java8 code snippet) before hand(as it is user input) hence can't choose subclass in my code. Is there any better way for this?










share|improve this question

























  • Have an array of string containing all the patterns. Write a custom parser. In the parser iterate through the array and try to parse. If it is not of that format, you will get ParseException. Catch it and continue through the loop. You can refer this link.

    – TRB
    Nov 23 '18 at 8:55











  • Your title does not match your Question. Your Question is about formatting patterns, but your title is about the various date-time types. Please correct this to keep Stack Overflow tidy.

    – Basil Bourque
    Nov 23 '18 at 17:01


















0















I want to convert pre Java8 like below.



DateFormat formatter = new SimpleDateFormat(timestampPattern, locale);
Date dt = formatter.parse(timestamp);
Date currentDateTime = getCurrentTime();


To Java 8 code to support more than 3 digits in milliseconds. I found ways to do that using the following simple code.



String parsedate="2016-03-16 01:14:21.6739";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
LocalDateTime newdate = LocalDateTime.parse(parsedate, dateTimeFormatter);


Problem with above code is that you have to know specific class before parsing it like if it contains only date in you have to use LocalDate and if only time LocalTime and if date + time + zone you have to use ZonedDateTime.



My problem is that I don't know timestampPattern or timestamp(Given in pre Java8 code snippet) before hand(as it is user input) hence can't choose subclass in my code. Is there any better way for this?










share|improve this question

























  • Have an array of string containing all the patterns. Write a custom parser. In the parser iterate through the array and try to parse. If it is not of that format, you will get ParseException. Catch it and continue through the loop. You can refer this link.

    – TRB
    Nov 23 '18 at 8:55











  • Your title does not match your Question. Your Question is about formatting patterns, but your title is about the various date-time types. Please correct this to keep Stack Overflow tidy.

    – Basil Bourque
    Nov 23 '18 at 17:01
















0












0








0








I want to convert pre Java8 like below.



DateFormat formatter = new SimpleDateFormat(timestampPattern, locale);
Date dt = formatter.parse(timestamp);
Date currentDateTime = getCurrentTime();


To Java 8 code to support more than 3 digits in milliseconds. I found ways to do that using the following simple code.



String parsedate="2016-03-16 01:14:21.6739";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
LocalDateTime newdate = LocalDateTime.parse(parsedate, dateTimeFormatter);


Problem with above code is that you have to know specific class before parsing it like if it contains only date in you have to use LocalDate and if only time LocalTime and if date + time + zone you have to use ZonedDateTime.



My problem is that I don't know timestampPattern or timestamp(Given in pre Java8 code snippet) before hand(as it is user input) hence can't choose subclass in my code. Is there any better way for this?










share|improve this question
















I want to convert pre Java8 like below.



DateFormat formatter = new SimpleDateFormat(timestampPattern, locale);
Date dt = formatter.parse(timestamp);
Date currentDateTime = getCurrentTime();


To Java 8 code to support more than 3 digits in milliseconds. I found ways to do that using the following simple code.



String parsedate="2016-03-16 01:14:21.6739";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
LocalDateTime newdate = LocalDateTime.parse(parsedate, dateTimeFormatter);


Problem with above code is that you have to know specific class before parsing it like if it contains only date in you have to use LocalDate and if only time LocalTime and if date + time + zone you have to use ZonedDateTime.



My problem is that I don't know timestampPattern or timestamp(Given in pre Java8 code snippet) before hand(as it is user input) hence can't choose subclass in my code. Is there any better way for this?







java datetime java-8






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 8:57









Naman

45.3k11102204




45.3k11102204










asked Nov 23 '18 at 8:40









AAjitAAjit

3110




3110













  • Have an array of string containing all the patterns. Write a custom parser. In the parser iterate through the array and try to parse. If it is not of that format, you will get ParseException. Catch it and continue through the loop. You can refer this link.

    – TRB
    Nov 23 '18 at 8:55











  • Your title does not match your Question. Your Question is about formatting patterns, but your title is about the various date-time types. Please correct this to keep Stack Overflow tidy.

    – Basil Bourque
    Nov 23 '18 at 17:01





















  • Have an array of string containing all the patterns. Write a custom parser. In the parser iterate through the array and try to parse. If it is not of that format, you will get ParseException. Catch it and continue through the loop. You can refer this link.

    – TRB
    Nov 23 '18 at 8:55











  • Your title does not match your Question. Your Question is about formatting patterns, but your title is about the various date-time types. Please correct this to keep Stack Overflow tidy.

    – Basil Bourque
    Nov 23 '18 at 17:01



















Have an array of string containing all the patterns. Write a custom parser. In the parser iterate through the array and try to parse. If it is not of that format, you will get ParseException. Catch it and continue through the loop. You can refer this link.

– TRB
Nov 23 '18 at 8:55





Have an array of string containing all the patterns. Write a custom parser. In the parser iterate through the array and try to parse. If it is not of that format, you will get ParseException. Catch it and continue through the loop. You can refer this link.

– TRB
Nov 23 '18 at 8:55













Your title does not match your Question. Your Question is about formatting patterns, but your title is about the various date-time types. Please correct this to keep Stack Overflow tidy.

– Basil Bourque
Nov 23 '18 at 17:01







Your title does not match your Question. Your Question is about formatting patterns, but your title is about the various date-time types. Please correct this to keep Stack Overflow tidy.

– Basil Bourque
Nov 23 '18 at 17:01














1 Answer
1






active

oldest

votes


















1














The following code will show you how you could deal with it:



String parsedate="2016-03-16 01:14:21.6739";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
TemporalAccessor parsed = dateTimeFormatter.parse(parsedate);
System.out.println(parsed.getClass());
// with the Parsed object you can then construct what you require... e.g. LocalDate:
System.out.println(LocalDate.from(parsed));
// or LocalDateTime:
System.out.println(LocalDateTime.from(parsed));


This prints:



class java.time.format.Parsed
2016-03-16
2016-03-16T01:14:21.673900


So you just have to use what you require in your code and build your LocalDate or LocalDateTime from the Parsed-object.



Note, that if the user can input only yyyy-MM-dd and you would have used such a date time format, then you will get problems creating the LocalDateTime from it, but I think you usually know which target type you require. Otherwise you could even just have worked with the TemporalAccessor instead.



In order to solve the specific date type issue you may need either to work against exceptions (try to parse it (or call from from the Parsed-object) and fallback to the next possible date format or type) or just check the format beforehand and use the appropriate date formatter and type then, which I rather recommend.






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443179%2fhow-to-choose-date-time-class-in-java8-among-localdatetime-zoneddatetime-and-ot%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The following code will show you how you could deal with it:



    String parsedate="2016-03-16 01:14:21.6739";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
    TemporalAccessor parsed = dateTimeFormatter.parse(parsedate);
    System.out.println(parsed.getClass());
    // with the Parsed object you can then construct what you require... e.g. LocalDate:
    System.out.println(LocalDate.from(parsed));
    // or LocalDateTime:
    System.out.println(LocalDateTime.from(parsed));


    This prints:



    class java.time.format.Parsed
    2016-03-16
    2016-03-16T01:14:21.673900


    So you just have to use what you require in your code and build your LocalDate or LocalDateTime from the Parsed-object.



    Note, that if the user can input only yyyy-MM-dd and you would have used such a date time format, then you will get problems creating the LocalDateTime from it, but I think you usually know which target type you require. Otherwise you could even just have worked with the TemporalAccessor instead.



    In order to solve the specific date type issue you may need either to work against exceptions (try to parse it (or call from from the Parsed-object) and fallback to the next possible date format or type) or just check the format beforehand and use the appropriate date formatter and type then, which I rather recommend.






    share|improve this answer






























      1














      The following code will show you how you could deal with it:



      String parsedate="2016-03-16 01:14:21.6739";
      DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
      TemporalAccessor parsed = dateTimeFormatter.parse(parsedate);
      System.out.println(parsed.getClass());
      // with the Parsed object you can then construct what you require... e.g. LocalDate:
      System.out.println(LocalDate.from(parsed));
      // or LocalDateTime:
      System.out.println(LocalDateTime.from(parsed));


      This prints:



      class java.time.format.Parsed
      2016-03-16
      2016-03-16T01:14:21.673900


      So you just have to use what you require in your code and build your LocalDate or LocalDateTime from the Parsed-object.



      Note, that if the user can input only yyyy-MM-dd and you would have used such a date time format, then you will get problems creating the LocalDateTime from it, but I think you usually know which target type you require. Otherwise you could even just have worked with the TemporalAccessor instead.



      In order to solve the specific date type issue you may need either to work against exceptions (try to parse it (or call from from the Parsed-object) and fallback to the next possible date format or type) or just check the format beforehand and use the appropriate date formatter and type then, which I rather recommend.






      share|improve this answer




























        1












        1








        1







        The following code will show you how you could deal with it:



        String parsedate="2016-03-16 01:14:21.6739";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
        TemporalAccessor parsed = dateTimeFormatter.parse(parsedate);
        System.out.println(parsed.getClass());
        // with the Parsed object you can then construct what you require... e.g. LocalDate:
        System.out.println(LocalDate.from(parsed));
        // or LocalDateTime:
        System.out.println(LocalDateTime.from(parsed));


        This prints:



        class java.time.format.Parsed
        2016-03-16
        2016-03-16T01:14:21.673900


        So you just have to use what you require in your code and build your LocalDate or LocalDateTime from the Parsed-object.



        Note, that if the user can input only yyyy-MM-dd and you would have used such a date time format, then you will get problems creating the LocalDateTime from it, but I think you usually know which target type you require. Otherwise you could even just have worked with the TemporalAccessor instead.



        In order to solve the specific date type issue you may need either to work against exceptions (try to parse it (or call from from the Parsed-object) and fallback to the next possible date format or type) or just check the format beforehand and use the appropriate date formatter and type then, which I rather recommend.






        share|improve this answer















        The following code will show you how you could deal with it:



        String parsedate="2016-03-16 01:14:21.6739";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
        TemporalAccessor parsed = dateTimeFormatter.parse(parsedate);
        System.out.println(parsed.getClass());
        // with the Parsed object you can then construct what you require... e.g. LocalDate:
        System.out.println(LocalDate.from(parsed));
        // or LocalDateTime:
        System.out.println(LocalDateTime.from(parsed));


        This prints:



        class java.time.format.Parsed
        2016-03-16
        2016-03-16T01:14:21.673900


        So you just have to use what you require in your code and build your LocalDate or LocalDateTime from the Parsed-object.



        Note, that if the user can input only yyyy-MM-dd and you would have used such a date time format, then you will get problems creating the LocalDateTime from it, but I think you usually know which target type you require. Otherwise you could even just have worked with the TemporalAccessor instead.



        In order to solve the specific date type issue you may need either to work against exceptions (try to parse it (or call from from the Parsed-object) and fallback to the next possible date format or type) or just check the format beforehand and use the appropriate date formatter and type then, which I rather recommend.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 '18 at 9:47

























        answered Nov 23 '18 at 8:58









        RolandRoland

        10.5k11442




        10.5k11442
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443179%2fhow-to-choose-date-time-class-in-java8-among-localdatetime-zoneddatetime-and-ot%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]