Java Calendar to String calendarToXSDString(Calendar cal, String fmt)

Here you can find the source of calendarToXSDString(Calendar cal, String fmt)

Description

calendar To XSD String

License

Apache License

Declaration

private static String calendarToXSDString(Calendar cal, String fmt) 

Method Source Code

//package com.java2s;
/*//from   ww w  .j ava 2s  . c o  m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import java.util.TimeZone;

public class Main {
    private static String calendarToXSDString(Calendar cal, String fmt) {
        // c.f. Constructor on Jena's XSDDateTime
        // Only issue is that it looses the timezone through (Xerces)
        // normalizing to UTC.
        SimpleDateFormat dFmt = new SimpleDateFormat(fmt);
        Date date = cal.getTime();
        String lex = dFmt.format(date);
        lex = lex + calcTimezone(cal);
        return lex;
    }

    private static String calcTimezone(Calendar cal) {
        Date date = cal.getTime();
        TimeZone z = cal.getTimeZone();
        int tzOff = z.getRawOffset();
        int tz = tzOff;

        if (z.inDaylightTime(date)) {
            int tzDst = z.getDSTSavings();
            tz = tz + tzDst;
        }

        String sign = "+";
        if (tz < 0) {
            sign = "-";
            tz = -tz;
        }

        int tzH = tz / (60 * 60 * 1000); // Integer divide towards zero.
        int tzM = (tz - tzH * 60 * 60 * 1000) / (60 * 1000);

        String tzH_str = Integer.toString(tzH);
        String tzM_str = Integer.toString(tzM);

        if (tzH < 10)
            tzH_str = "0" + tzH_str;
        if (tzM < 10)
            tzM_str = "0" + tzM_str;
        return sign + tzH_str + ":" + tzM_str;
    }
}

Related

  1. calendarToString(Calendar calendar)
  2. calendarToString(Calendar calendar)
  3. calendarToString(Calendar calendar, String template)
  4. calendarToString(Calendar date, boolean transformToLocalTime)
  5. CalendarToString(Calendar fecha, String formato)
  6. dateToCalendar(final String date)
  7. dateToString(Calendar date, DateFormat format)
  8. getDateString(Calendar cal)
  9. getDateString(Calendar cal)