Get current time, yyyy-MM-dd hh:mm:ss. - Android java.util

Android examples for java.util:Time

Description

Get current time, yyyy-MM-dd hh:mm:ss.

Demo Code

/*// www  . j a  v  a2  s  .com
 * Copyright (C) 2016 venshine.cn@gmail.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.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main{
    public static final String DATE_FORMAT = "yyyyMMdd";
    public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss:ms";
    /**
     * Get current time, yyyy-MM-dd hh:mm:ss.
     *
     * @return
     */
    public static String getTime() {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat(TIME_FORMAT);
        return df.format(now);
    }
    /**
     * Convert long time to String time
     *
     * @param time
     * @param format
     * @return
     */
    public static String getTime(long time, String format) {
        if (time > 0) {
            if (StringUtils.isEmpty(format)) {
                format = DATE_FORMAT;
            }
            SimpleDateFormat sf = new SimpleDateFormat(format);
            Date date = new Date(time);
            return sf.format(date);
        }
        return "";
    }
    /**
     * Convert String time to long time
     *
     * @param time
     * @param format
     * @return
     */
    public static long getTime(String time, String format) {
        try {
            if (null != time) {
                if (format == null) {
                    format = DATE_FORMAT;
                }
                SimpleDateFormat sf = new SimpleDateFormat(format);
                return sf.parse(time).getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

Related Tutorials