My backend is built using java and the user settings API returns datetime formats to use within the view using Java standards (datetimes are later returned in ISO8601 and formatted on the fly). Example in Java 'yyyy-MM-dd' should be converted to 'YYYY-MM-DD' to be used with javascript's library momentjs.
Is there a direct way to convert symbols from java to javascript libraries (momentjs or date-fns)?
CodePudding user response:
momentjs has its own specific format symbols which was confusing, whereas other libraries like date-fns are following the LDML standard. I ended up using date-fns as Java is having the same standard.
https://date-fns.org/v2.26.0/docs/Unicode-Tokens
https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
CodePudding user response:
This will be a pretty hand-held operation. Also you may not be able to cover all cases, but certainly the most common ones. The following should get you started.
function replacer(match, offset, string) {
switch (match) {
case 'M': return 'M';
case 'MM': return 'MM';
case 'MMM': return 'MMM';
case 'MMMM': return 'MMMM';
case 'd': return 'D';
case 'dd': return 'DD';
case 'D': return 'DDD';
case 'DDD': return 'DDDD';
case 'yy': return 'YY';
case 'yyyy': return 'YYYY';
default: return '(not supported)';
}
}
var javaPattern = 'yyyy-MM-dd';
var regEx = /([a-z] )/g;
var javaScriptPattern = javaPattern.replace(regEx, replacer);
console.log(javaScriptPattern);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Please go through the Java pattern letters and the JavaScript pattern letters in the two links below and expand the translations in my code as needed.
Links
- Java format pattern letters are in the documetnation of
DateTimeFormatter
- momentjs format pattern letters are in Format - momentjs.com