Format date to string in yyyy-MM-dd HH:mm:ss.SSS format - Android java.util

Android examples for java.util:Date Time

Description

Format date to string in yyyy-MM-dd HH:mm:ss.SSS format

Demo Code

import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    public static String date2str(Date date) {
        try {/*from  ww  w . j ava 2 s  .c o  m*/
            if (date == null)
                return "";
            SimpleDateFormat sdf = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
            return sdf.format(date);
        } catch (Exception e) {
        }
        return "";
    }
    public static String date2str(Date date, String style) throws Exception {
        if (date == null || style == null)
            return "";
        SimpleDateFormat sdf = new SimpleDateFormat(style);
        return sdf.format(date);
    }

}

Related Tutorials