Java Date Format Change changeDateFormat(String dateString, String srcFormat, String destFormat)

Here you can find the source of changeDateFormat(String dateString, String srcFormat, String destFormat)

Description

Convert the string date to a particular format.

License

Open Source License

Parameter

Parameter Description
dateString The String to operate on.
srcFormat The date Format contained in the String.
destFormat The format to be converted to.

Return

Formatted Date String if successful, null otherwise.

Declaration

public static String changeDateFormat(String dateString, String srcFormat, String destFormat) 

Method Source Code

//package com.java2s;
/**/*from  w ww.  java2s. c  o  m*/
 * (C) 2010-2011 Alibaba Group Holding Limited.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 
 * version 2 as published by the Free Software Foundation. 
 * 
 */

import java.text.ParsePosition;
import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
    /**
     * Convert the string date to a particular format.
     * 
     * @param   dateString
     *          The String to operate on.
     *            
     * @param   srcFormat
     *          The date Format contained in the String.
     *            
     * @param   destFormat
     *          The format to be converted to.
     *            
     * @return 
     *          Formatted Date String if successful, null otherwise.
     * 
     */
    public static String changeDateFormat(String dateString, String srcFormat, String destFormat) {
        if (srcFormat == null || destFormat == null || srcFormat.isEmpty() || destFormat.isEmpty()) {
            return "";
        }

        // Set the Date Format for the vaules in the column specified
        SimpleDateFormat dateFormat = new SimpleDateFormat(srcFormat);

        if (dateString == null || dateString.isEmpty()) {
            return "";
        }

        // Get date as per the format
        java.util.Date dateVal = dateFormat.parse(dateString, new ParsePosition(0));

        dateFormat = new SimpleDateFormat(destFormat);

        return dateFormat.format(dateVal);
    }

    public static String changeDateFormat(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

        return dateFormat.format(date);
    }
}

Related

  1. changeDateFormatPattern(final DateFormat dateFormat, String regex, String replacement)
  2. changeDateTimeZone(String date_GMT)
  3. changeDateValue(Date firstDate, Date secondDate)
  4. convertDate(String date, String sourceFormat, String destinationFormat)