Any help or hint would be greatly appreciated. From the below code I get this date:2023-01-25 16:30:22.998. How can I get this date: "FrmDt": "2023-01-16T23:59:59.938Z". It has a "T" which I not sure what this mean?
java.util.Date tsFrom = new java.util.Date();
Calendar calFrom = Calendar.getInstance();
calFrom.setTime(tsFrom);
calFrom.add(Calendar.YEAR, -1);
tsFrom.setTime(calFrom.getTime().getTime()); // or
sqlTSFromDate = new Timestamp(calFrom.getTime().getTime());
System.out.println("From date:" sqlTSFromDate);
CodePudding user response:
tl;dr
Instant
.now()
.minus(
Period.ofYears( 1 )
)
.toString()
ISO 8601
Study the ISO 8601 standard formats for textually representing date-time values.
Avoid legacy classes
Never use the legacy classes Date
, Calendar
, Timestamp
. They are terribly flawed, designed by people who did not understand date-time handling.
java.time
Instead, use the java.time classes defined in JSR 310.
Apparently you want one year prior to the the current moment as seen in UTC. To represent a moment in UTC, use java.time.Instant
class.
Instant oneYearAgoInUtc =
Instant
.now()
.minus(
Period.ofYears( 1 )
)
;
To generate text in standard ISO 8601, merely call toString
. The java.time classes use ISO 8601 formats by default when generating/parsing text.
String output = oneYearAgoInUtc.toString() ;
The T
separates the year-month-day portion from the hour-minute-second portion.
The Z
indicates an offset from UTC of zero hours-minutes-seconds.
CodePudding user response:
As several comments said, this is an ISO 8601 date. In java, you can parse or write using SimpleDateFormat. With the Z at the end, makle sure to use UTC/Zulu time.
Amending your code:
public static String ISO_8601 = "yyyyMMdd'T'HHmmss'Z'";
...
SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
sqlTSFromDate = dateFormat.format(tsFrom)