Java Date Convert DateToStr(java.util.Date val)

Here you can find the source of DateToStr(java.util.Date val)

Description

This converts a java.util.Date to a date string in the form of YYYY-MM-DD.

License

Open Source License

Parameter

Parameter Description
val The date to convert

Return

The date converted to a string in the format of YYYY-MM-DD

Declaration

static public String DateToStr(java.util.Date val) 

Method Source Code


//package com.java2s;

import java.util.Calendar;

public class Main {
    /**/*from w w w  .  ja va 2 s  . c o  m*/
     * This converts a java.util.Date to a date string in the form of YYYY-MM-DD. If a null 
     * is sent in then the current date is used for the conversion and returned
     * as a string.
     * 
     * @param val The date to convert
     * @return The date converted to a string in the format of YYYY-MM-DD
     */
    static public String DateToStr(java.util.Date val) {
        Calendar cal = Calendar.getInstance();
        StringBuffer sb = new StringBuffer();
        String year, month, day;

        if (val != null) {
            cal.setTime(val);
        }

        year = "" + cal.get(Calendar.YEAR);
        month = "" + (cal.get(Calendar.MONTH) + 1);
        day = "" + cal.get(Calendar.DAY_OF_MONTH);

        sb.append(padZeroString(year, 4) + "-");
        sb.append(padZeroString(month, 2) + "-");
        sb.append(padZeroString(day, 2));

        return sb.toString();
    }

    /**
    * This simply pads a string with 0s out to a specified length.
    *
    * @param val the string that is to be padded
    * @param size the length the string should be
    * @return the padded string
    */
    static public String padZeroString(String val, int size) {
        /* Initialize local variables */
        int count = 0;
        String retVal;

        val = val.trim();
        if (val == null) {
            val = "";
        }
        StringBuffer result = new StringBuffer(val);

        if (val.length() > size) {
            result.setLength(size);
        }

        /* Build a char array */
        for (count = val.length(); count < size; count++) {
            result.insert(0, "0");
        }

        retVal = result.toString();
        return retVal;
    }
}

Related

  1. DateToMask(Date javaDateType)
  2. dateToMorining(Date date)
  3. dateToNumber(Date date)
  4. dateToQTime(final Date date)
  5. dateToRRNDate(Date date)
  6. dateToString(Date date)
  7. dateToString(Date date)
  8. dateToString(Date date)
  9. dateToString(final Date date)