首页 > 代码库 > Java "JSON中无分隔符日期字符串处理"

Java "JSON中无分隔符日期字符串处理"

Json 中日期类型数据处理,服务端传输的日期没有分隔符,一般格式就两种,[20151212121212]即yyyyMMddhhmmss和[121212]hhmmss

import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Locale;public class test {    public static void main(String[] args)    {        String strDateTime="20150206201756";        String strTime="201756";                System.out.println(convJsonDateToString(strDateTime,"yyyy-MM-dd hh:mm:ss"));        System.out.println(convJsonDateToString(strTime,"hhmmss","hh:mm:ss"));    }    public static String convJsonDateToString(String jsonDate,String stringTemplate){                String resultString=null;        try {            Calendar cldCalendar=convToCalender(jsonDate, "yyyyMMddhhmmss");            resultString=convToString(cldCalendar, stringTemplate);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return resultString;    }    public static String convJsonDateToString(String jsonDate,String jsonTemplate,String stringTemplate){                String resultString=null;        try {            Calendar cldCalendar=convToCalender(jsonDate, jsonTemplate);            resultString=convToString(cldCalendar, stringTemplate);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return resultString;    }    // 把指定格式的日期字符串转日期类型    public static Calendar convToCalender(String str,String template){        SimpleDateFormat sdf;        Date date;        Calendar cltResult = Calendar.getInstance();        sdf = new SimpleDateFormat(template, Locale.getDefault());        try {            date = sdf.parse(str);            cltResult.setTime(date);        } catch (Exception ex) {            // TODO Auto-generated catch block            ex.printStackTrace();        }        return cltResult;    }    // 把日期转指定格式字符串    public static String convToString(Calendar cld,String template){        String resultString=null;        try {            Date date=cld.getTime();            SimpleDateFormat sdf=new SimpleDateFormat(template,Locale.getDefault());            resultString=sdf.format(date);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return resultString;    }}

 

Java "JSON中无分隔符日期字符串处理"