Java Calendar to Time getTimeString(Calendar calendar)

Here you can find the source of getTimeString(Calendar calendar)

Description

get Time String

License

Open Source License

Declaration

private static String getTimeString(Calendar calendar) 

Method Source Code


//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    private static String getTimeString(Calendar calendar) {
        StringBuffer sb = new StringBuffer();
        sb.append(String.valueOf(calendar.get(Calendar.YEAR)))
                .append(valueOfString(String.valueOf(calendar.get(Calendar.MONTH) + 1), 2))
                .append(valueOfString(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)), 2))
                .append(valueOfString(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)), 2))
                .append(valueOfString(String.valueOf(calendar.get(Calendar.MINUTE)), 2))
                .append(valueOfString(String.valueOf(calendar.get(Calendar.SECOND)), 2))
                .append(valueOfString(String.valueOf(calendar.get(Calendar.MILLISECOND)), 3));
        return sb.toString();
    }/*from   www .j av a 2  s . c om*/

    public static String getTimeString(String time) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(getDateFormat(time));
        return getTimeString(calendar);
    }

    public static String getTimeString() {
        Calendar calendar = new GregorianCalendar();
        return getTimeString(calendar);
    }

    private static String valueOfString(String str, int len) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len - str.length(); i++) {
            sb.append("0");
        }
        return (sb.length() == 0) ? (str) : (sb.toString() + str);
    }

    public static String getDateFormat() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }

    public static Date getDateFormat(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. getTime(Calendar c)
  2. getTime(Calendar calendar)
  3. getTime(Calendar calendar)
  4. getTime(Calendar pCalendar_)
  5. getTimeString(Calendar cal)
  6. printTime(Calendar value)