Is there any utility which converts 00 date to the last day of the month.
For example, if we have string date "220400" where 22 is the year 01 is the month and 00 is the given date. Can we convert this to 220430 using any utility in java code?
Currently our system converts "220400" to 220331.
CodePudding user response:
Your Question is unclear. Do you want to work with the previous month or the indicated month?
YearMonth
Either way, parse your string as a YearMonth
.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuMM'00'" ) ;
YearMonth ym = YearMonth.parse( input , f ) ;
From there you can use minusMonths
method to move to previous month if desired.
Call atDay( 1 )
to get first of month. Call atEndOfMonth
to get last day.
LocalDate ld = ym.minusMonths( 1 ).atEndOfMonth() ;
See this code run live at Ideone.com.
Tip: Educate the publisher of your data about the ISO 8601 standard of formats for communicating date-time values as text.
CodePudding user response:
If 00
currently gives the last day of the previous month, couldn't you just check if the last two digits are 00, and if so, increment the month portion.
(using JS here for a runnable snippet but the concept is the same):
// Your original get date function, presumably if you put in
// 200500 you'd get 220430
const originalGetDate = (dt) => {
// Since people don't seem to understand this was an example
// if (dt === "220500") return "220430";
const pieces = dt.match(/.{1,2}/g);
const [year, month, day] = pieces;
console.log({year, month, day})
const d = new Date(`20${year}`, `${month-1}`)
d.setDate(day)
return d;
}
const getDate = (dt) => {
// get your date pieces: [22, 04, 00]
const pieces = dt.match(/.{1,2}/g);
// if the last piece is 00, increment the previous
if (pieces[2] == "00") pieces[1] = ("" (parseInt(pieces[1]) 1)).padStart(2, '0');
// If we're in a new year after this, increment the year
if (pieces[1] == "13") {
pieces[0] = ("" (parseInt(pieces[0]) 1)).padStart(2, '0');
}
// then call the original function
return originalGetDate(pieces.join(""))
}
console.log(getDate('220400'))