Java Calendar to String calendarToString(Calendar cal, String format)

Here you can find the source of calendarToString(Calendar cal, String format)

Description

calendar To String

License

Apache License

Declaration

public static String calendarToString(Calendar cal, String format) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2015 Bin Liu (flylb1@gmail.com)
 *   /*www  . j a  va  2 s  .  com*/
 * Licensed 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.util.Calendar;

public class Main {
    public static String calendarToString(Calendar cal, String format) {
        StringBuffer sb = new StringBuffer();
        if (cal == null) {
            return "";
        }
        if (format.indexOf("yyyy/") != -1) {
            sb.append(cal.get(Calendar.YEAR));
            sb.append("/");
        }
        if (format.indexOf("MM/") != -1) {
            sb.append(cal.get(Calendar.MONTH) + 1);
            sb.append("/");
        }
        if (format.indexOf("dd") != -1) {
            sb.append(cal.get(Calendar.DATE));
            sb.append(" ");
        }
        if (format.indexOf("hh") != -1) {
            if (format.indexOf("hh:") != -1) {
                sb.append(cal.get(Calendar.HOUR_OF_DAY));
                sb.append(":");
            } else {
                sb.append(cal.get(Calendar.HOUR_OF_DAY));
            }
        }
        if (format.indexOf("mm") != -1) {
            if (format.indexOf("mm:") != -1) {
                sb.append(cal.get(Calendar.MINUTE));
                sb.append(":");
            } else {
                sb.append(cal.get(Calendar.MINUTE));
            }
        }

        if (format.indexOf("ss") != -1) {
            sb.append(cal.get(Calendar.SECOND));
        }

        return sb.toString();
    }
}

Related

  1. calendarToStorageRoomTimeString(Calendar cal)
  2. calendarToString(Calendar c)
  3. calendarToString(Calendar c, String format)
  4. calendarToString(Calendar cal)
  5. calendarToString(Calendar cal)
  6. calendarToString(Calendar calendar)
  7. calendarToString(Calendar calendar)
  8. calendarToString(Calendar calendar)
  9. calendarToString(Calendar calendar, String template)