What is the best way to convert XMLGregorianCalendar to MM/dd/yyyy hh:mm String?

前端 未结 5 716
无人共我
无人共我 2021-02-04 00:18

What is the best way to convert XMLGregorianCalendar objects to \'MM/dd/yyyy hh:mm\' String?

相关标签:
5条回答
  • 2021-02-04 00:42

    This example convert XMLGregorianCalendar to date

    XMLGregorianCalendar xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
    Date date = xmlCalendar.toGregorianCalendar().getTime();
    

    This example convert date to string

    DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm");
    String dateStr = df.format(GregorianCalendar.getInstance().getTime());
    
    0 讨论(0)
  • 2021-02-04 00:49

    You can use toGregorianCalendar() method for this.

    E.g.:

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
    String date = sdf.format(xmlGregorianCalendar.toGregorianCalendar().getTime());
    

    In case, you need to convert that calendar to different TimeZone and Locale, use toGregorianCalendar(TimeZone timezone, Locale aLocale, XMLGregorianCalendar defaults)

    0 讨论(0)
  • 2021-02-04 00:49

    Please check this static utility. You just mentioned a pattern like "ddMMyy" or "HHmm" or what ever you want.. this will work wonderfully.

    public static String getDateTime(XMLGregorianCalendar gDate, String pattern){
    
        return Optional.ofNullable(gDate)
                .map(gdate -> {
                    Calendar calendar = gDate.toGregorianCalendar();
                    SimpleDateFormat formatter = new SimpleDateFormat(pattern);
                    formatter.setTimeZone(calendar.getTimeZone());
                    return formatter.format(calendar.getTime());
                })
                .orElse(null);
    }
    
    0 讨论(0)
  • 2021-02-04 00:51

    First use XMLGregorianCalendar#toGregorianCalendar() to get a java.util.Calendar instance out of it.

    Calendar calendar = xmlGregorianCalendar.toGregorianCalendar();
    

    From that step on, it's all obvious with a little help of SimpleDateFormat the usual way.

    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm");
    formatter.setTimeZone(calendar.getTimeZone());
    String dateString = formatter.format(calendar.getTime());
    

    I only wonder if you don't actually want to use HH instead of hh as you aren't formatting the am/pm marker anywhere.

    0 讨论(0)
  • 2021-02-04 00:51

    This is an example you are looking for:

    XMLGregorianCalendar date = ...; // initialization is out of scope for this example
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
    GregorianCalendar gc = date.toGregorianCalendar();
    String formatted_string = sdf.format(gc.getTime());
    
    0 讨论(0)
提交回复
热议问题