Format String in 'YYYY-MM-DD' to Timestamp - Android java.util

Android examples for java.util:Date Format

Description

Format String in 'YYYY-MM-DD' to Timestamp

Demo Code

/*//from w  ww  .  ja v a  2  s .  c om
 * File: $RCSfile: FormatUtilities.java,v $
 *
 * Copyright (c) 2005 Wincor Nixdorf International GmbH,
 * Heinz-Nixdorf-Ring 1, 33106 Paderborn, Germany
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Wincor Nixdorf ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered
 * into with Wincor Nixdorf.
 */
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main{
    public static final String SHORT_DATE_FORMAT = "yyyy-MM-dd";
    /**
     * Format String in 'YYYY-MM-DD' to Timestamp
     *
     * @param dateStr String to Convert
     * @return Formatted Timestamp
     */
    public static Timestamp strToTimestamp(final String dateStr) {
        Date dat = strToDate(dateStr);
        return new Timestamp(dat.getTime());
    }
    /**
     * Format String in 'YYYY-MM-DD' to Date
     *
     * @param dateStr String to Convert
     * @return Formatted Date
     */
    public static Date strToDate(final String dateStr) {
        return strToDate(dateStr, SHORT_DATE_FORMAT, Locale.US);
    }
    /**
     * Format String in Pattern to Date
     *
     * @param dateStr String to Convert
     * @param pattern Convert Pattern
     * @return Formatted Date
     */
    public static Date strToDate(final String dateStr, final String pattern) {
        return strToDate(dateStr, pattern, Locale.US);
    }
    /**
     * Format String in Pattern and Locale to Date
     *
     * @param dateStr String to Convert
     * @param pattern Convert Pattern
     * @param loc     Convert Locale
     * @return Formatted Date
     */
    public static Date strToDate(final String dateStr,
            final String pattern, final Locale loc) {
        if (StringUtilities.isEmpty(dateStr)) {
            return null;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern, loc);
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            Log.e(FormatUtilities.class.getName(), e.getMessage());
            return null;
        }
    }
}

Related Tutorials