Difficulty formatting dates in GroovyHow to return only the Date from a SQL Server DateTime datatypeCompare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?Scala vs. Groovy vs. ClojureDetecting an “invalid date” Date instance in JavaScriptYYYY-MM-DD format date in shell scriptHow do I get the current date in JavaScript?How to format a JavaScript dateJava string to date conversionChange date format in a Java string

What is the fastest integer factorization to break RSA?

Implication of namely

How do I exit BASH while loop using modulus operator?

What exactly is ineptocracy?

Do creatures with a listed speed of "0 ft., fly 30 ft. (hover)" ever touch the ground?

Is there a hemisphere-neutral way of specifying a season?

My ex-girlfriend uses my Apple ID to log in to her iPad. Do I have to give her my Apple ID password to reset it?

Why was Sir Cadogan fired?

Does int main() need a declaration on C++?

my venezuela girlfriend wants to travel the USA where i live.what does she need to do and how expensive will it become or how difficult?

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

What is an equivalently powerful replacement spell for the Yuan-Ti's Suggestion spell?

Ambiguity in the definition of entropy

How to install cross-compiler on Ubuntu 18.04?

How do conventional missiles fly?

How exploitable/balanced is this homebrew spell: Spell Permanency?

How badly should I try to prevent a user from XSSing themselves?

Why were 5.25" floppy drives cheaper than 8"?

What is required to make GPS signals available indoors?

Could the museum Saturn V's be refitted for one more flight?

Is it possible to map the firing of neurons in the human brain so as to stimulate artificial memories in someone else?

Where would I need my direct neural interface to be implanted?

Solving an equation with constraints

Can a virus destroy the BIOS of a modern computer?



Difficulty formatting dates in Groovy


How to return only the Date from a SQL Server DateTime datatypeCompare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?Scala vs. Groovy vs. ClojureDetecting an “invalid date” Date instance in JavaScriptYYYY-MM-DD format date in shell scriptHow do I get the current date in JavaScript?How to format a JavaScript dateJava string to date conversionChange date format in a Java string













2















I am having some issues formatting dates in Groovy. I am trying to convert a string back to a localdate and its not taking it so well....



DateTimeFormatter formatDates = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");

LocalDate currentLocalDate = LocalDate.now();
// modify the local date to the previous day
LocalDate previousDateLocalDate = currentLocalDate.minusDays(1)
// cast localdates to strings
String startDateString = previousDateLocalDate.toString() + " 00:00"
String endDateString = previousDateLocalDate.toString() + " 23:59"
// cast strings to localdates
LocalDate startDateLocalDate = LocalDate.parse(startDateString, formatDates);


The output is only showing what was in the previousDateLocalDate variable :
2019-03-06



I am not sure why its dropping the hh:mm. Could it be my format or is my syntax wrong. Any ideas would be greatly appreciated. Is it possible when I subtract a day off from my current day to just format it how I need it to be there instead or set the format when I create the LocalDate.now()?



-Thanks



Edit 1: Let me also add that the minusDays may vary so there might be a better way to get the previous day before yesterday but in some cases it might be 7, 11, etc...










share|improve this question



















  • 1





    Local Date doesn't have time

    – tim_yates
    Mar 7 at 21:32











  • so i should convert this then to a new date()? Is there a way to just format the date in Date itself? every example is parsing and formatting back and forth. I just want a simple 1 line solution. I am not sure what the purpose of all these different ways of expressing dates and times could possibly be used for lol....

    – The Chem X
    Mar 7 at 21:35






  • 1





    If you want to have access to time just use LocalDateTime

    – Reza
    Mar 7 at 21:40















2















I am having some issues formatting dates in Groovy. I am trying to convert a string back to a localdate and its not taking it so well....



DateTimeFormatter formatDates = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");

LocalDate currentLocalDate = LocalDate.now();
// modify the local date to the previous day
LocalDate previousDateLocalDate = currentLocalDate.minusDays(1)
// cast localdates to strings
String startDateString = previousDateLocalDate.toString() + " 00:00"
String endDateString = previousDateLocalDate.toString() + " 23:59"
// cast strings to localdates
LocalDate startDateLocalDate = LocalDate.parse(startDateString, formatDates);


The output is only showing what was in the previousDateLocalDate variable :
2019-03-06



I am not sure why its dropping the hh:mm. Could it be my format or is my syntax wrong. Any ideas would be greatly appreciated. Is it possible when I subtract a day off from my current day to just format it how I need it to be there instead or set the format when I create the LocalDate.now()?



-Thanks



Edit 1: Let me also add that the minusDays may vary so there might be a better way to get the previous day before yesterday but in some cases it might be 7, 11, etc...










share|improve this question



















  • 1





    Local Date doesn't have time

    – tim_yates
    Mar 7 at 21:32











  • so i should convert this then to a new date()? Is there a way to just format the date in Date itself? every example is parsing and formatting back and forth. I just want a simple 1 line solution. I am not sure what the purpose of all these different ways of expressing dates and times could possibly be used for lol....

    – The Chem X
    Mar 7 at 21:35






  • 1





    If you want to have access to time just use LocalDateTime

    – Reza
    Mar 7 at 21:40













2












2








2








I am having some issues formatting dates in Groovy. I am trying to convert a string back to a localdate and its not taking it so well....



DateTimeFormatter formatDates = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");

LocalDate currentLocalDate = LocalDate.now();
// modify the local date to the previous day
LocalDate previousDateLocalDate = currentLocalDate.minusDays(1)
// cast localdates to strings
String startDateString = previousDateLocalDate.toString() + " 00:00"
String endDateString = previousDateLocalDate.toString() + " 23:59"
// cast strings to localdates
LocalDate startDateLocalDate = LocalDate.parse(startDateString, formatDates);


The output is only showing what was in the previousDateLocalDate variable :
2019-03-06



I am not sure why its dropping the hh:mm. Could it be my format or is my syntax wrong. Any ideas would be greatly appreciated. Is it possible when I subtract a day off from my current day to just format it how I need it to be there instead or set the format when I create the LocalDate.now()?



-Thanks



Edit 1: Let me also add that the minusDays may vary so there might be a better way to get the previous day before yesterday but in some cases it might be 7, 11, etc...










share|improve this question
















I am having some issues formatting dates in Groovy. I am trying to convert a string back to a localdate and its not taking it so well....



DateTimeFormatter formatDates = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");

LocalDate currentLocalDate = LocalDate.now();
// modify the local date to the previous day
LocalDate previousDateLocalDate = currentLocalDate.minusDays(1)
// cast localdates to strings
String startDateString = previousDateLocalDate.toString() + " 00:00"
String endDateString = previousDateLocalDate.toString() + " 23:59"
// cast strings to localdates
LocalDate startDateLocalDate = LocalDate.parse(startDateString, formatDates);


The output is only showing what was in the previousDateLocalDate variable :
2019-03-06



I am not sure why its dropping the hh:mm. Could it be my format or is my syntax wrong. Any ideas would be greatly appreciated. Is it possible when I subtract a day off from my current day to just format it how I need it to be there instead or set the format when I create the LocalDate.now()?



-Thanks



Edit 1: Let me also add that the minusDays may vary so there might be a better way to get the previous day before yesterday but in some cases it might be 7, 11, etc...







java string date grails groovy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 21:32







The Chem X

















asked Mar 7 at 21:20









The Chem XThe Chem X

174




174







  • 1





    Local Date doesn't have time

    – tim_yates
    Mar 7 at 21:32











  • so i should convert this then to a new date()? Is there a way to just format the date in Date itself? every example is parsing and formatting back and forth. I just want a simple 1 line solution. I am not sure what the purpose of all these different ways of expressing dates and times could possibly be used for lol....

    – The Chem X
    Mar 7 at 21:35






  • 1





    If you want to have access to time just use LocalDateTime

    – Reza
    Mar 7 at 21:40












  • 1





    Local Date doesn't have time

    – tim_yates
    Mar 7 at 21:32











  • so i should convert this then to a new date()? Is there a way to just format the date in Date itself? every example is parsing and formatting back and forth. I just want a simple 1 line solution. I am not sure what the purpose of all these different ways of expressing dates and times could possibly be used for lol....

    – The Chem X
    Mar 7 at 21:35






  • 1





    If you want to have access to time just use LocalDateTime

    – Reza
    Mar 7 at 21:40







1




1





Local Date doesn't have time

– tim_yates
Mar 7 at 21:32





Local Date doesn't have time

– tim_yates
Mar 7 at 21:32













so i should convert this then to a new date()? Is there a way to just format the date in Date itself? every example is parsing and formatting back and forth. I just want a simple 1 line solution. I am not sure what the purpose of all these different ways of expressing dates and times could possibly be used for lol....

– The Chem X
Mar 7 at 21:35





so i should convert this then to a new date()? Is there a way to just format the date in Date itself? every example is parsing and formatting back and forth. I just want a simple 1 line solution. I am not sure what the purpose of all these different ways of expressing dates and times could possibly be used for lol....

– The Chem X
Mar 7 at 21:35




1




1





If you want to have access to time just use LocalDateTime

– Reza
Mar 7 at 21:40





If you want to have access to time just use LocalDateTime

– Reza
Mar 7 at 21:40












2 Answers
2






active

oldest

votes


















1














Specify time zone explicitly



You should always specify explicitly the desired/expected time zone when calling now. For any given moment, the date varies around the globe by time zone. It might be “tomorrow” in Tokyo Japan while “yesterday” in Casablanca Morocco. When you omit the zone, the JVM’s current default zone is implicitly applied at runtime – so your results may vary.



ZoneId z = ZoneId.of( "Africa/Casablanca" ) ; // Or `ZoneId.systemDefault` if you actually want the JVM’s current default time zone.
LocalDate ld = LocalDate.now( z ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).


LocalDate



LocalDate class represents only a date, without time-of-day and without time zone or offset-from-UTC.



If you wish to combine a time-of-day with a date, use one of the other classes.



table showing modern versus legacy classes used to represent a moment



Date-time math



The java.time classes offer plus… and minus… methods for adding or subtracting a span of time.



LocalDate yesterday = ld.minusDays( 1 ) ;


First moment of the day



Apparently you want the first moment of a date. A couple things to understand here. Firstly, a time zone is needed. As discussed above, a new day dawns at different moments around the globe by zone. Secondly, do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day on some dates in same zones may start at another time, such as 01:00:00. Let java.time determine the first moment.



ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of the day.


Half-Open



Apparently you want the end of day. Tracking the last moment of the day is problematic. For example, your 23:59 text will miss any moment of that last minute of the day.



Generally, a better approach to tracking spans of time is the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a day starts with the first moment of the day and runs up to, but does not include, the first moment of the next day.



ZonedDateTime start = ld.atStartOfDay( z ) ; // Start of today.
ZonedDateTime stop = ld.plusDays( 1 ).atStartOfDay( z ) ; // Start of tomorrow.


DateTimeFormatter



To generate strings representing your date-time object’s value, use a DateTimeFormatter object. I’ll not cover that here, as it has been covered many many many times already on Stack Overflow.



DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm" ) ;
String output = zdt.format( f ) ; // Generate text representing the value of this `ZonedDateTime` object.


Keep in mind that date-time objects do not have a “format”, only a textual representation of a date-time object’s value has a format. Do not conflate the string object with the date-time object. A date-time object can parse a string, and can generate a string, but is not itself a string.






share|improve this answer
































    -1














    try this tool



    import grails.gorm.transactions.Transactional
    import org.springframework.stereotype.Component

    import java.time.LocalDate
    import java.time.Period
    import java.time.ZoneId
    import java.time.chrono.ChronoLocalDate
    import java.time.chrono.Chronology
    import java.time.chrono.MinguoChronology
    import java.time.format.DateTimeFormatter
    import java.time.format.DateTimeFormatterBuilder
    import java.time.format.DecimalStyle
    import java.time.temporal.TemporalAccessor
    import java.time.temporal.TemporalAdjusters


     Date mgStringToDate(String mgString, String separator = "/") 

    if(mgString)
    Locale locale = Locale.getDefault(Locale.Category.FORMAT);
    Chronology chrono = MinguoChronology.INSTANCE;
    DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient()
    .appendPattern("yyy$separatorMM$separatordd").toFormatter().withChronology(chrono)
    .withDecimalStyle(DecimalStyle.of(locale));
    TemporalAccessor temporal = df.parse(mgString);
    ChronoLocalDate cDate = chrono.date(temporal);
    Date date = Date.from(LocalDate.from(cDate).atStartOfDay(ZoneId.systemDefault()).toInstant());
    return date
    else
    return null








    share|improve this answer


















    • 1





      You should edit your answer to include a brief explanation of what your code does, and how it helps to solve issues with formatting. This makes it more useful to those who come across the same issue later on.

      – Hoppeduppeanut
      Mar 8 at 3:21











    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%2f55052968%2fdifficulty-formatting-dates-in-groovy%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Specify time zone explicitly



    You should always specify explicitly the desired/expected time zone when calling now. For any given moment, the date varies around the globe by time zone. It might be “tomorrow” in Tokyo Japan while “yesterday” in Casablanca Morocco. When you omit the zone, the JVM’s current default zone is implicitly applied at runtime – so your results may vary.



    ZoneId z = ZoneId.of( "Africa/Casablanca" ) ; // Or `ZoneId.systemDefault` if you actually want the JVM’s current default time zone.
    LocalDate ld = LocalDate.now( z ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).


    LocalDate



    LocalDate class represents only a date, without time-of-day and without time zone or offset-from-UTC.



    If you wish to combine a time-of-day with a date, use one of the other classes.



    table showing modern versus legacy classes used to represent a moment



    Date-time math



    The java.time classes offer plus… and minus… methods for adding or subtracting a span of time.



    LocalDate yesterday = ld.minusDays( 1 ) ;


    First moment of the day



    Apparently you want the first moment of a date. A couple things to understand here. Firstly, a time zone is needed. As discussed above, a new day dawns at different moments around the globe by zone. Secondly, do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day on some dates in same zones may start at another time, such as 01:00:00. Let java.time determine the first moment.



    ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of the day.


    Half-Open



    Apparently you want the end of day. Tracking the last moment of the day is problematic. For example, your 23:59 text will miss any moment of that last minute of the day.



    Generally, a better approach to tracking spans of time is the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a day starts with the first moment of the day and runs up to, but does not include, the first moment of the next day.



    ZonedDateTime start = ld.atStartOfDay( z ) ; // Start of today.
    ZonedDateTime stop = ld.plusDays( 1 ).atStartOfDay( z ) ; // Start of tomorrow.


    DateTimeFormatter



    To generate strings representing your date-time object’s value, use a DateTimeFormatter object. I’ll not cover that here, as it has been covered many many many times already on Stack Overflow.



    DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm" ) ;
    String output = zdt.format( f ) ; // Generate text representing the value of this `ZonedDateTime` object.


    Keep in mind that date-time objects do not have a “format”, only a textual representation of a date-time object’s value has a format. Do not conflate the string object with the date-time object. A date-time object can parse a string, and can generate a string, but is not itself a string.






    share|improve this answer





























      1














      Specify time zone explicitly



      You should always specify explicitly the desired/expected time zone when calling now. For any given moment, the date varies around the globe by time zone. It might be “tomorrow” in Tokyo Japan while “yesterday” in Casablanca Morocco. When you omit the zone, the JVM’s current default zone is implicitly applied at runtime – so your results may vary.



      ZoneId z = ZoneId.of( "Africa/Casablanca" ) ; // Or `ZoneId.systemDefault` if you actually want the JVM’s current default time zone.
      LocalDate ld = LocalDate.now( z ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).


      LocalDate



      LocalDate class represents only a date, without time-of-day and without time zone or offset-from-UTC.



      If you wish to combine a time-of-day with a date, use one of the other classes.



      table showing modern versus legacy classes used to represent a moment



      Date-time math



      The java.time classes offer plus… and minus… methods for adding or subtracting a span of time.



      LocalDate yesterday = ld.minusDays( 1 ) ;


      First moment of the day



      Apparently you want the first moment of a date. A couple things to understand here. Firstly, a time zone is needed. As discussed above, a new day dawns at different moments around the globe by zone. Secondly, do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day on some dates in same zones may start at another time, such as 01:00:00. Let java.time determine the first moment.



      ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of the day.


      Half-Open



      Apparently you want the end of day. Tracking the last moment of the day is problematic. For example, your 23:59 text will miss any moment of that last minute of the day.



      Generally, a better approach to tracking spans of time is the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a day starts with the first moment of the day and runs up to, but does not include, the first moment of the next day.



      ZonedDateTime start = ld.atStartOfDay( z ) ; // Start of today.
      ZonedDateTime stop = ld.plusDays( 1 ).atStartOfDay( z ) ; // Start of tomorrow.


      DateTimeFormatter



      To generate strings representing your date-time object’s value, use a DateTimeFormatter object. I’ll not cover that here, as it has been covered many many many times already on Stack Overflow.



      DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm" ) ;
      String output = zdt.format( f ) ; // Generate text representing the value of this `ZonedDateTime` object.


      Keep in mind that date-time objects do not have a “format”, only a textual representation of a date-time object’s value has a format. Do not conflate the string object with the date-time object. A date-time object can parse a string, and can generate a string, but is not itself a string.






      share|improve this answer



























        1












        1








        1







        Specify time zone explicitly



        You should always specify explicitly the desired/expected time zone when calling now. For any given moment, the date varies around the globe by time zone. It might be “tomorrow” in Tokyo Japan while “yesterday” in Casablanca Morocco. When you omit the zone, the JVM’s current default zone is implicitly applied at runtime – so your results may vary.



        ZoneId z = ZoneId.of( "Africa/Casablanca" ) ; // Or `ZoneId.systemDefault` if you actually want the JVM’s current default time zone.
        LocalDate ld = LocalDate.now( z ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).


        LocalDate



        LocalDate class represents only a date, without time-of-day and without time zone or offset-from-UTC.



        If you wish to combine a time-of-day with a date, use one of the other classes.



        table showing modern versus legacy classes used to represent a moment



        Date-time math



        The java.time classes offer plus… and minus… methods for adding or subtracting a span of time.



        LocalDate yesterday = ld.minusDays( 1 ) ;


        First moment of the day



        Apparently you want the first moment of a date. A couple things to understand here. Firstly, a time zone is needed. As discussed above, a new day dawns at different moments around the globe by zone. Secondly, do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day on some dates in same zones may start at another time, such as 01:00:00. Let java.time determine the first moment.



        ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of the day.


        Half-Open



        Apparently you want the end of day. Tracking the last moment of the day is problematic. For example, your 23:59 text will miss any moment of that last minute of the day.



        Generally, a better approach to tracking spans of time is the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a day starts with the first moment of the day and runs up to, but does not include, the first moment of the next day.



        ZonedDateTime start = ld.atStartOfDay( z ) ; // Start of today.
        ZonedDateTime stop = ld.plusDays( 1 ).atStartOfDay( z ) ; // Start of tomorrow.


        DateTimeFormatter



        To generate strings representing your date-time object’s value, use a DateTimeFormatter object. I’ll not cover that here, as it has been covered many many many times already on Stack Overflow.



        DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm" ) ;
        String output = zdt.format( f ) ; // Generate text representing the value of this `ZonedDateTime` object.


        Keep in mind that date-time objects do not have a “format”, only a textual representation of a date-time object’s value has a format. Do not conflate the string object with the date-time object. A date-time object can parse a string, and can generate a string, but is not itself a string.






        share|improve this answer















        Specify time zone explicitly



        You should always specify explicitly the desired/expected time zone when calling now. For any given moment, the date varies around the globe by time zone. It might be “tomorrow” in Tokyo Japan while “yesterday” in Casablanca Morocco. When you omit the zone, the JVM’s current default zone is implicitly applied at runtime – so your results may vary.



        ZoneId z = ZoneId.of( "Africa/Casablanca" ) ; // Or `ZoneId.systemDefault` if you actually want the JVM’s current default time zone.
        LocalDate ld = LocalDate.now( z ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).


        LocalDate



        LocalDate class represents only a date, without time-of-day and without time zone or offset-from-UTC.



        If you wish to combine a time-of-day with a date, use one of the other classes.



        table showing modern versus legacy classes used to represent a moment



        Date-time math



        The java.time classes offer plus… and minus… methods for adding or subtracting a span of time.



        LocalDate yesterday = ld.minusDays( 1 ) ;


        First moment of the day



        Apparently you want the first moment of a date. A couple things to understand here. Firstly, a time zone is needed. As discussed above, a new day dawns at different moments around the globe by zone. Secondly, do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day on some dates in same zones may start at another time, such as 01:00:00. Let java.time determine the first moment.



        ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Let java.time determine the first moment of the day.


        Half-Open



        Apparently you want the end of day. Tracking the last moment of the day is problematic. For example, your 23:59 text will miss any moment of that last minute of the day.



        Generally, a better approach to tracking spans of time is the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a day starts with the first moment of the day and runs up to, but does not include, the first moment of the next day.



        ZonedDateTime start = ld.atStartOfDay( z ) ; // Start of today.
        ZonedDateTime stop = ld.plusDays( 1 ).atStartOfDay( z ) ; // Start of tomorrow.


        DateTimeFormatter



        To generate strings representing your date-time object’s value, use a DateTimeFormatter object. I’ll not cover that here, as it has been covered many many many times already on Stack Overflow.



        DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm" ) ;
        String output = zdt.format( f ) ; // Generate text representing the value of this `ZonedDateTime` object.


        Keep in mind that date-time objects do not have a “format”, only a textual representation of a date-time object’s value has a format. Do not conflate the string object with the date-time object. A date-time object can parse a string, and can generate a string, but is not itself a string.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 7 at 23:37

























        answered Mar 7 at 23:16









        Basil BourqueBasil Bourque

        117k30395559




        117k30395559























            -1














            try this tool



            import grails.gorm.transactions.Transactional
            import org.springframework.stereotype.Component

            import java.time.LocalDate
            import java.time.Period
            import java.time.ZoneId
            import java.time.chrono.ChronoLocalDate
            import java.time.chrono.Chronology
            import java.time.chrono.MinguoChronology
            import java.time.format.DateTimeFormatter
            import java.time.format.DateTimeFormatterBuilder
            import java.time.format.DecimalStyle
            import java.time.temporal.TemporalAccessor
            import java.time.temporal.TemporalAdjusters


             Date mgStringToDate(String mgString, String separator = "/") 

            if(mgString)
            Locale locale = Locale.getDefault(Locale.Category.FORMAT);
            Chronology chrono = MinguoChronology.INSTANCE;
            DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient()
            .appendPattern("yyy$separatorMM$separatordd").toFormatter().withChronology(chrono)
            .withDecimalStyle(DecimalStyle.of(locale));
            TemporalAccessor temporal = df.parse(mgString);
            ChronoLocalDate cDate = chrono.date(temporal);
            Date date = Date.from(LocalDate.from(cDate).atStartOfDay(ZoneId.systemDefault()).toInstant());
            return date
            else
            return null








            share|improve this answer


















            • 1





              You should edit your answer to include a brief explanation of what your code does, and how it helps to solve issues with formatting. This makes it more useful to those who come across the same issue later on.

              – Hoppeduppeanut
              Mar 8 at 3:21















            -1














            try this tool



            import grails.gorm.transactions.Transactional
            import org.springframework.stereotype.Component

            import java.time.LocalDate
            import java.time.Period
            import java.time.ZoneId
            import java.time.chrono.ChronoLocalDate
            import java.time.chrono.Chronology
            import java.time.chrono.MinguoChronology
            import java.time.format.DateTimeFormatter
            import java.time.format.DateTimeFormatterBuilder
            import java.time.format.DecimalStyle
            import java.time.temporal.TemporalAccessor
            import java.time.temporal.TemporalAdjusters


             Date mgStringToDate(String mgString, String separator = "/") 

            if(mgString)
            Locale locale = Locale.getDefault(Locale.Category.FORMAT);
            Chronology chrono = MinguoChronology.INSTANCE;
            DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient()
            .appendPattern("yyy$separatorMM$separatordd").toFormatter().withChronology(chrono)
            .withDecimalStyle(DecimalStyle.of(locale));
            TemporalAccessor temporal = df.parse(mgString);
            ChronoLocalDate cDate = chrono.date(temporal);
            Date date = Date.from(LocalDate.from(cDate).atStartOfDay(ZoneId.systemDefault()).toInstant());
            return date
            else
            return null








            share|improve this answer


















            • 1





              You should edit your answer to include a brief explanation of what your code does, and how it helps to solve issues with formatting. This makes it more useful to those who come across the same issue later on.

              – Hoppeduppeanut
              Mar 8 at 3:21













            -1












            -1








            -1







            try this tool



            import grails.gorm.transactions.Transactional
            import org.springframework.stereotype.Component

            import java.time.LocalDate
            import java.time.Period
            import java.time.ZoneId
            import java.time.chrono.ChronoLocalDate
            import java.time.chrono.Chronology
            import java.time.chrono.MinguoChronology
            import java.time.format.DateTimeFormatter
            import java.time.format.DateTimeFormatterBuilder
            import java.time.format.DecimalStyle
            import java.time.temporal.TemporalAccessor
            import java.time.temporal.TemporalAdjusters


             Date mgStringToDate(String mgString, String separator = "/") 

            if(mgString)
            Locale locale = Locale.getDefault(Locale.Category.FORMAT);
            Chronology chrono = MinguoChronology.INSTANCE;
            DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient()
            .appendPattern("yyy$separatorMM$separatordd").toFormatter().withChronology(chrono)
            .withDecimalStyle(DecimalStyle.of(locale));
            TemporalAccessor temporal = df.parse(mgString);
            ChronoLocalDate cDate = chrono.date(temporal);
            Date date = Date.from(LocalDate.from(cDate).atStartOfDay(ZoneId.systemDefault()).toInstant());
            return date
            else
            return null








            share|improve this answer













            try this tool



            import grails.gorm.transactions.Transactional
            import org.springframework.stereotype.Component

            import java.time.LocalDate
            import java.time.Period
            import java.time.ZoneId
            import java.time.chrono.ChronoLocalDate
            import java.time.chrono.Chronology
            import java.time.chrono.MinguoChronology
            import java.time.format.DateTimeFormatter
            import java.time.format.DateTimeFormatterBuilder
            import java.time.format.DecimalStyle
            import java.time.temporal.TemporalAccessor
            import java.time.temporal.TemporalAdjusters


             Date mgStringToDate(String mgString, String separator = "/") 

            if(mgString)
            Locale locale = Locale.getDefault(Locale.Category.FORMAT);
            Chronology chrono = MinguoChronology.INSTANCE;
            DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient()
            .appendPattern("yyy$separatorMM$separatordd").toFormatter().withChronology(chrono)
            .withDecimalStyle(DecimalStyle.of(locale));
            TemporalAccessor temporal = df.parse(mgString);
            ChronoLocalDate cDate = chrono.date(temporal);
            Date date = Date.from(LocalDate.from(cDate).atStartOfDay(ZoneId.systemDefault()).toInstant());
            return date
            else
            return null









            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 8 at 3:17









            TaiwaneseDavidChengTaiwaneseDavidCheng

            161




            161







            • 1





              You should edit your answer to include a brief explanation of what your code does, and how it helps to solve issues with formatting. This makes it more useful to those who come across the same issue later on.

              – Hoppeduppeanut
              Mar 8 at 3:21












            • 1





              You should edit your answer to include a brief explanation of what your code does, and how it helps to solve issues with formatting. This makes it more useful to those who come across the same issue later on.

              – Hoppeduppeanut
              Mar 8 at 3:21







            1




            1





            You should edit your answer to include a brief explanation of what your code does, and how it helps to solve issues with formatting. This makes it more useful to those who come across the same issue later on.

            – Hoppeduppeanut
            Mar 8 at 3:21





            You should edit your answer to include a brief explanation of what your code does, and how it helps to solve issues with formatting. This makes it more useful to those who come across the same issue later on.

            – Hoppeduppeanut
            Mar 8 at 3:21

















            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%2f55052968%2fdifficulty-formatting-dates-in-groovy%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

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко