简体   繁体   中英

Difficulty formatting dates in Groovy

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...

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.

该表显示了用于表示时刻的现代与传统类

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.

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${separator}MM${separator}dd").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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM