開發中,往往在背景把帶有日期類型的一些資料直接轉成json然後綁定到前台的樣式清單控件裡,在控件裡擷取或者綁定時,Date類型往往都變成了如
{"date":26,"day":1,"hours":11,"minutes":30,"month":9,"seconds":18,"time":1256527818296,"timezoneOffset":-480,"year":109}這樣的格式,js擷取時,為一個這樣的對象而不是我們想要的“2014-11-11”這樣的日期格式。
如果我們這時我們就需要把這樣的日起格式化成我們所常見的格式,如果想在JS頁面使用,可使用下邊方法:
定義一個如下方法:
function formatDate(v, dateFormat) {
try {
if (dateFormat == undefined || typeof dateFormat != "string") {
dateFormat = "yyyy-MM-dd";
}
if ((typeof v) == "number"){
var o = new Date(v*1000);
return o.pattern(dateFormat);
}
if ((typeof v) == "string" && v.indexOf("/Date(") == 0) {
var date = eval('new ' + eval(v).source);
return date.pattern(dateFormat);
}
if (v.time) {
var o = new Date(v.time);
return o.pattern(dateFormat);
}
else {
if (v != "") {
v = v.replace(/\//g, "-");
if(v=="1900-01-01 00:00:00"){
return "--";
}
if (v.split(" ")) {
var myDate = v.split(" ")[0];
} else {
var myDate = v;
var myTime = "";
}
myDate = myDate.replace("-0", "-").replace("-0", "-");
var nowDate = new Date();
/*TD 7111*/
if(myDate.split("-")[0]=="1900"){
return "--";
}
if (myDate.split("-")[0] == nowDate.getFullYear()) {//本年度 For td 5858
return myDate.split("-")[0] + "年" + myDate.split("-")[1] + "月" + myDate.split("-")[2] + "日";
} else {//非本年度
return myDate.split("-")[0] + "年" + myDate.split("-")[1] + "月" + myDate.split("-")[2] + "日";
}
}else{
return "--";
}
}
}catch (e) { }
return "--";
};
然後把對應的json日期字元串以參數形式傳給定義好的函數formatDate,如果直接formatDate(jsonDate),就是傳回預設的格式的日期如“2014-11-11”,如果這樣使用formatDate(jsonDate,"yyyy年MM月dd日")可以以指定的日期格式傳回。
如果是在java中遇到這樣情況,想在java解決,在此引用一個網友的解決方法:
//注冊date類型的轉化方式
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessorImplTest());
JSONObject jsonFromBean = JSONObject.fromObject(testBean,jsonConfig);
System.out.println(jsonFromBean);
//prints {"birthday":"2009-10-26","id":"id","name":"name"}
String[] dateFormats = new String[] {"yyyy/MM/dd","yyyy-MM-dd"};
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
TestBean jsonToBean = (TestBean)JSONObject.toBean(jsonFromBean,TestBean.class);
System.out.println(jsonToBean);
//prints [email protected][id=id,name=name,birthday=Mon Oct 26 00:00:00 CST 2009]
其中需要的類如下:
1.準備測試資料
import java.util.Date;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
public class TestBean {
private String id;
private String name;
private java.util.Date birthday;
public TestBean() {
super();
}
public TestBean(String id, String name, Date birthday) {
super();
this.id = id;
this.name = name;
this.birthday = birthday;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.util.Date getBirthday() {
return birthday;
}
public void setBirthday(java.util.Date birthday) {
this.birthday = birthday;
}
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
2.建立Date格式化類
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class JsonValueProcessorImplTest implements JsonValueProcessor {
private String format = "yyyy-MM-dd";
public JsonValueProcessorImplTest() {
super();
}
public JsonValueProcessorImplTest(String format) {
super();
this.format = format;
}
@Override
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
String[] obj = {};
if (value instanceof Date[]) {
SimpleDateFormat sf = new SimpleDateFormat(format);
Date[] dates = (Date[]) value;
obj = new String[dates.length];
for (int i = 0; i < dates.length; i++) {
obj[i] = sf.format(dates[i]);
}
}
return obj;
}
@Override
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
if (value instanceof java.util.Date) {
String str = new SimpleDateFormat(format).format((Date) value);
return str;
}
return value.toString();
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
通過如上方式我們就可以把含date類型的javabean在javabean和json格式中互相轉化了,此java方法來自名為lyking2001
的ITeye上的網友。
其實我們也可以把這個作為一個字元串分别拆分年、月、日來,然後簡單計算(如用目前日期測試拆開得到的對應各個日期段的內插補點,然後就可以與真實的參數拆開進行計算)後拼在一起也是可以的,js和java都可以這樣處理,隻不過技術含量不高但簡單易了解。