专业的JAVA编程教程与资源

网站首页 > java教程 正文

java数字转成大写汉字(java数字转换成大写字母)

temp10 2024-10-29 16:35:48 java教程 13 ℃ 0 评论

我遇到过这么一个需求,在电子文书中,需要签名盖章及生成对应的日期,但日期不是我们平时使用的格式,而是中文日期,如二零一九年九月六号。这种需求尤其在银行的行业中,可能会要求把数字金钱转成中文来表示。相信有些小伙伴也会遇到这样的需求,以下贴出我的工具类。

/**
 * 获取大写当前时间
 * 
 * @return
 */
public static String getDateBigDate(Date date) {
 if (date == null) {
 return "";
 }
 return getStrBigDate(ServiceCommon.YMD.format(date));
}
/**
 * 获取大写时间
 * 
 * @return
 */
public static String getStrBigDate(String date) {
 return DateToUpperChinese.toChinese(date);
}
package com.weitu.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 日期转成中文大写形式
 *
 */
public class DateToUpperChinese {
 private static final String[] NUMBERS = {"0", "一", "二", "三", "四", "五",
 "六", "七", "八", "九"};
// private static final String[] NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍",
// "陆", "柒", "捌", "玖"};
 /**
 * 通过 yyyy-MM-dd 得到中文大写格式 yyyy MM dd 日期
 */
 public static synchronized String toChinese(String str) {
 StringBuffer sb = new StringBuffer();
 sb.append(getSplitDateStr(str, 0)).append("年").append(
 getSplitDateStr(str, 1)).append("月").append(
 getSplitDateStr(str, 2)).append("日");
 return sb.toString();
 }
 /**
 * 分别得到年月日的大写 默认分割符 "-"
 */
 public static String getSplitDateStr(String str, int unit) {
 // unit是单位 0=年 1=月 2日
 String[] DateStr = str.split("-");
 if (unit > DateStr.length)
 unit = 0;
 StringBuffer sb = new StringBuffer();
 for (int i = 0; i < DateStr[unit].length(); i++) {
 if ((unit == 1 || unit == 2) && Integer.valueOf(DateStr[unit]) > 9) {
 sb.append(convertNum(DateStr[unit].substring(0, 1)))
 .append("十").append(
 convertNum(DateStr[unit].substring(1, 2)));
 break;
 }else if(unit == 1 && "0".equals(DateStr[unit].substring(0, i + 1))){
 continue;
 }else if(unit == 2 && "0".equals(DateStr[unit].substring(0, i + 1))){
 continue;
 }
 else {
 sb.append(convertNum(DateStr[unit].substring(i, i + 1)));
 }
 }
 if (unit == 1 || unit == 2) {
 return sb.toString().replaceAll("^壹", "").replace("零", "");
 }
 return sb.toString();
 }
 /**
 * 转换数字为大写
 */
 private static String convertNum(String str) {
 return NUMBERS[Integer.valueOf(str)];
 }
 /**
 * 判断是否是零或正整数
 */
 public static boolean isNumeric(String str) {
 Pattern pattern = Pattern.compile("[0-9]*");
 Matcher isNum = pattern.matcher(str);
 if (!isNum.matches()) {
 return false;
 }
 return true;
 }
}

测试结果:

java数字转成大写汉字(java数字转换成大写字母)

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表