今天做项目,需要数字类型的时间转换为中文类型的时间,这是一个java数字时间类型转中文类型的方法,适用于文档使用等等。和对时间有特殊要求的项目。通俗易懂很容易看懂。不多说了直接上代码
首先用时间函数获取想要的格式的时间
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Demo {
private static String getChineseDate(String riqi) throws Exception {
String[] newsdate = new String[8];
for (int i = 0; i < riqi.length(); i++) {
int k = Integer.parseInt(Character.toString(riqi.charAt(i)));
switch (k) {
case 0:
newsdate[i] = "〇";
break;
case 1:
newsdate[i] = "一";
break;
case 2:
newsdate[i] = "二";
break;
case 3:
newsdate[i] = "三";
break;
case 4:
newsdate[i] = "四";
break;
case 5:
newsdate[i] = "五";
break;
case 6:
newsdate[i] = "六";
break;
case 7:
newsdate[i] = "七";
break;
case 8:
newsdate[i] = "八";
break;
case 9:
newsdate[i] = "九";
break;
}
}
// 加入年月日
List<String> s1 = new ArrayList<String>();
for (int i = 0; i < 8; i++) {
if (i < 4) {
s1.add(newsdate[i]);
} else if (i == 4) {
s1.add("年");
s1.add(newsdate[i]);
} else if (i == 5) {
s1.add(newsdate[i]);
} else if (i == 6) {
s1.add("月");
s1.add(newsdate[i]);
} else if (i == 7) {
s1.add(newsdate[i]);
s1.add("日");
}
}
String newstr = "";
for (String s : s1) {
newstr += s;
}
/*
* 截取月份、日期
*/
int i = newstr.indexOf("年");
int j = newstr.indexOf("月");
String month = newstr.substring(i + 1, j);
String day = newstr.substring(j + 1, newstr.length() - 1);
/*
* 处理月份
*/
String str1 = month.substring(0, 1);
String str2 = month.substring(1);
String newmonth = "";
if ("〇".equals(str1)) {
newmonth = str2;
} else if ("一".equals(str1) && "〇".equals(str2)) {
newmonth = "十";
} else if ("一".equals(str1) && !"〇".equals(str2)) {
newmonth = "十" + str2;
}
/*
* 处理日期
*/
String st1 = day.substring(0, 1);
String st2 = day.substring(1);
String newday = "";
if ("〇".equals(st1)) {
newday = st2;
} else if ("一".equals(st1) && "〇".equals(st2)) {
newday = "十";
} else if ("一".equals(st1) && !"〇".equals(st2)) {
newday = "十" + st2;
} else if ("二".equals(st1) && "〇".equals(st2)) {
newday = st1 + "十";
} else if ("二".equals(st1) && !"〇".equals(st2)) {
newday = st1 + "十" + st2;
} else if ("三".equals(st1) && "〇".equals(st2)) {
newday = st1 + "十";
} else if ("三".equals(st1) && !"〇".equals(st2)) {
newday = st1 + "十" + st2;
}
String newstring = newstr.substring(0, i) + "年" + newmonth + "月" + newday + "日";
return newstring;
}
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String riqi = sdf.format(new Date());
System.out.println(getChineseDate(riqi));
} catch (Exception e) {
e.printStackTrace();
}
}
}输出示例:二〇一六年九月二十六日
未经允许请勿转载:程序喵 » JAVA的时间类型转换为中文大写方法
程序喵