今天遇到個日期的錯誤,在系統中取到的日期值爲:Wed Jul 26 00:00:00 CST 2017
顯然不是我想要的類型,可以通過SimpleDateFormat 進行格式化轉換爲自己想要的類型
例如:
// 假設這裏的日期值爲 Date date = Wed Jul 26 00:00:00 CST 2017; // 不要較真,只是方面看 SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy"); // 只要年 SimpleDateFormat sdfMoth = new SimpleDateFormat("MM"); // 只要月 SimpleDateFormat sdfDay = new SimpleDateFormat("dd"); // 只要天 SimpleDateFormat sdfAll = new SimpleDateFormat("yyyy-MM-dd"); // 年月日 sdfYear.format(date); // 2017 sdfMoth.format(date); // 7 sdfDay.format(date); // 26 sdfAll.format(date); // 2017-07-26 當然這裏還可以是其他格式,根據自己需求而定。
package com.test.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * * @author zhuweishi * 隨機字符串 公共方法類 */ public class RundomString { /** * @param len 字符長度 * @return * 返回隨機數字 */ public static String getNumberString(int len){ String str = ""; for (int i = 0; i < len; i++) { int d = (int)(Math.random()*10); str += d; } return str; } /** * @param len 字符長度 * @return * 返回隨機大小寫字母和數字 */ public static String getLowerNumberString(int len){ String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for(int i = 0;i < len;i++){ sb.append(str.charAt(random.nextInt(62))); } return sb.toString(); } /** * @param * date 需要轉換的日期 * format 需要轉換的合格 例如 yyyy-MM-dd HH:mm:ss.SSS * @return * 以特定格式化日期 */ public static String getDateString(Date date,String format){ SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); } /** * @param date 日期 * @param len 後追加 字符隨機長度 * @return * 返回 日期和字符 */ public static String getDateNumberString(Date date,int len){ String gns = getNumberString(len); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return sdf.format(date) + gns; } /** * @param date 日期 * @param len 字符長度 * @return * 返回 日期和 len 長度的 隨機大小寫字母和數字 */ public static String getDateLowerNumberString(Date date,int len){ String gns = getLowerNumberString(len); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return sdf.format(date) + gns; } }