Java-8 – delete the “05:30” section from java8 localdatetime to xmlregistry calender
As shown below,
LocalDateTime currentUTCTime = LocalDateTime.Now(ZoneId.of("UTC")); String reqPattern = currentUTCTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS")); System.out.println("required pattern: " + reqPattern); GregorianCalendar calendar = GregorianCalendar.from(currentUTCTime.atZone(ZoneId.systemDefault())); XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); System.out.println("But Showing As :" + xcal);
I want the output to be 2015-06-18 11:59:15:135, but when I set xcal to use the XML tag of xmlregion calender, as shown in 2015-06-18t11:59:15.135 05:30
How do I delete the 05:30 section?
Solution
Use this Code:
LocalDateTime currentUTCTime = LocalDateTime.Now(); // using system timezone String iso = currentUTCTime.toString(); if (currentUTCTime.getSecond() == 0 && currentUTCTime.getNano() == 0) { iso += ":00"; // necessary hack because the second part is not optional in XML } XMLGregorianCalendar xml = DatatypeFactory.newInstance().newXMLGregorianCalendar(iso);
explain:
The code uses the given factory method and expects the dictionary representation of the local timestamp in iso-8601 format Because localdatetime does not reference any time zone, the output through tostring() cannot contain a time zone offset Result: xmlregionancalendar treats the time zone offset as "not set"
corrections:
The original code does not pay special attention to currentutctime ISO variant of formatted output of tostring() However, if these parts are equal to zero, Java The time API generates output without seconds or nanoseconds This is perfectly legal in ISO, but the W3C alliance makes part II non optional The class xmlregionancalendar pays close attention to this deviation from the specification Therefore, in this special edge case, use a simple string to connect the hack shown above Thank you very much for @ Dave's comments Incidentally, you can also use the currentutctime suggested in this comment Format (datetimeformatter. Iso_date_time) (instead of the displayed hack)