今天遇到个日期的错误,在系统中取到的日期值为: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;
}
}本文出自 “永恒之光” 博客,请务必保留此出处http://zhuws.blog.51cto.com/11134439/1951439
原文:http://zhuws.blog.51cto.com/11134439/1951439