Skip to content

Instantly share code, notes, and snippets.

@kobachi
Created June 17, 2014 06:50
Show Gist options
  • Save kobachi/d1c269e870f54dc27a65 to your computer and use it in GitHub Desktop.
Save kobachi/d1c269e870f54dc27a65 to your computer and use it in GitHub Desktop.
System.Convert (C#) like Type Convert Utility Classes for Java
package kobachi.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Strings;
import kobachi.util.DateFormatType;
/**
* 型の相互変換を行うユーティリティ(フォーム対応)
* デフォルト値を考えるときは Optional.fromNullable() を使ってください。
*
*/
public class ConvertUtil {
/**
* 文字列をboolean値に変換します。
* @param value
* @return !Strings.isNullOrEmpty(value)
*/
public static boolean toBoolean(@Nullable String value) {
return Strings.isNullOrEmpty(value) ? false : "true".equals(value.toLowerCase());
}
/**
* Integer値をboolean値に変換します。
* @param value
* @return value == 1ならtrue、nullまたはその他の値ならfalse
*/
public static boolean toBoolean(@Nullable Integer value) {
return (value != null && value == 1);
}
/**
* Boolean値を文字列に変換します。
* @param value
* @return trueなら"true"、nullまたはfalseなら"false"
*/
public static String toString(@Nullable Boolean value) {
return toString(value, "true", "false");
}
/**
* 変換後の文字列を指定して、Boolean値を文字列に変換します。
* @param value
* @param onTrue trueの時の文字列
* @param onFalse nullまたはfalseの時の文字列
* @return
*/
@Nullable
public static String toString(@Nullable Boolean value, @Nullable String onTrue, @Nullable String onFalse) {
return (value != null && value) ? onTrue : onFalse;
}
/** 数値 */
private static final Pattern numericStringPattern = Pattern.compile("^\\-?[0-9,]+(\\.[0-9]+)?$");
/**
* 指定された文字列が小数点部を持つか返します。
* @param value
* @return
*/
public static boolean hasDecimalPoint(@Nullable String value) {
if (value == null) {
return false;
}
Matcher m = numericStringPattern.matcher(value);
if (!m.matches()) {
return false;
}
return m.group(1) != null;
}
/**
* 数値文字列を、parseできる形に修正する
* @param value 修正したい文字列
* @param removeComma コンマを削除する場合はtrue
* @param removeDecimalPoint 小数点部を削除する場合はtrue
* @return 修正できた場合は修正後の文字列。数値文字列でなければnull
*/
@Nullable
public static String formatNumeric(@Nullable String value, boolean removeComma, boolean removeDecimalPoint) {
if (value == null) {
return null;
}
Matcher m = numericStringPattern.matcher(value);
if (!m.matches()) {
return null;
}
String v = value;
if (removeDecimalPoint && m.group(1) != null) {
v = v.substring(0, m.start(1));
}
if (removeComma && v.contains(",")) {
v = v.replaceAll(",", "");
}
return v;
}
/**
* 文字列値をLong値に変換します。小数点部を含む場合は無視されます。
* 「,」を含んでいても変換できます。
* @param value
* @return
*/
@Nullable
public static Long toLong(@Nullable String value) {
if(value == null){
return null;
}
String v = formatNumeric(value, true, true);
return (v != null) ? Long.parseLong(value) : null;
}
/**
* Long値を文字列値に変換します。
* @param value
* @return
*/
@Nullable
public static String toString(@Nullable Long value) {
return (value != null) ? value.toString() : null;
}
/**
* 文字列をInteger値に変換します。小数点部を含む場合は無視されます。
* 「,」を含んでいても変換できます。
* @param value
* @return 変換できない値ならnull
*/
@Nullable
public static Integer toInteger(@Nullable String value) {
if(value == null){
return null;
}
String v = formatNumeric(value, true, true);
return (v != null) ? Integer.valueOf(v) : null;
}
/**
* Boolean値をInteger値に変換します。
* @param value
* @return trueなら1、nullまたはfalseならnull
*/
@Nullable
public static Integer toInteger(@Nullable Boolean value) {
return (value != null && value) ? 1 : null;
}
/**
* Integer値を文字列値に変換します。
* @param value
* @return nullならnull
*/
@Nullable
public static String toString(@Nullable Integer value) {
return (value != null) ? value.toString() : null;
}
/**
* 文字列をShort値に変換します。Shortの範囲外になった場合はnullを返します。
* 「,」を含んでいても変換できます。
* @param value
* @return
*/
@Nullable
public static Short toShort(@Nullable String value) {
Integer intval = toInteger(value);
if (intval == null) {
return null;
}
if (intval < Short.MIN_VALUE || Short.MAX_VALUE < intval) {
return null;
}
return intval.shortValue();
}
/**
* Short値を文字列値に変換します。
* @param value
* @return
*/
@Nullable
public static String toString(@Nullable Short value) {
return (value != null) ? value.toString() : null;
}
/**
* 文字列をByte値に変換します。Byteの範囲外になった場合はnullを返します。
* @param value
* @return
*/
@Nullable
public static Byte toByte(@Nullable String value) {
Integer intval = toInteger(value);
if (intval == null) {
return null;
}
if (intval < Byte.MIN_VALUE || Byte.MAX_VALUE < intval) {
return null;
}
return intval.byteValue();
}
/**
* Byte値を文字列値に変換します。
* @param value
* @return
*/
@Nullable
public static String toString(@Nullable Byte value) {
if (value == null) {
return null;
}
return value.toString();
}
/**
* 文字列値をFloat値に変換します。
* 「,」を含んでいても変換できます。
* @param value
* @return
*/
@Nullable
public static Float toFloat(@Nullable String value) {
if (value == null) {
return null;
}
String v = formatNumeric(value, true, false);
return (v != null) ? Float.valueOf(v) : null;
}
/**
* Float値を文字列値に変換します。
* @param value
* @return
*/
@Nullable
public static String toString(@Nullable Float value) {
return (value != null) ? value.toString() : null;
}
/**
* 文字列値をDoule値に変換します。
* 「,」を含んでいても変換できます。
* @param value
* @return
*/
@Nullable
public static Double toDouble(@Nullable String value) {
if (value == null) {
return null;
}
String v = formatNumeric(value, true, false);
return (v != null) ? Double.valueOf(v) : null;
}
/**
* Double値を文字列値に変換します。
* @param value
* @return
*/
@Nullable
public static String toString(@Nullable Double value) {
return (value != null) ? value.toString() : null;
}
/**
* Double値を文字列値に変換します。
* @param value
* @param ignoreDecimalZero 小数点部の「.0」を省略する場合はtrue
* @return
*/
@Nullable
public static String toString(@Nullable Double value, boolean ignoreDecimalZero) {
if (value == null) {
return null;
}
String v = value.toString();
return (ignoreDecimalZero && v.endsWith(".0")) ? v.substring(0, v.length() - 2) : v;
}
/**
* 文字列値をDate値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static Date toDate(@Nullable String date, String format) {
if (date == null) {
return null;
}
try {
return new SimpleDateFormat(format).parse(date);
} catch (ParseException e) {
return null;
}
}
/**
* 文字列値をDate値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static Date toDate(@Nullable String date, DateFormatType format) {
if (format == null) {
throw new IllegalArgumentException("formatパラメータはnullにできません。");
}
return toDate(date, format.getFormatString());
}
/**
* 文字列をjava.sql.Date値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static java.sql.Date toSqlDate(@Nullable String date, String format) {
Date d = toDate(date, format);
if (d == null) {
return null;
}
return new java.sql.Date(d.getTime());
}
/**
* 文字列をjava.sql.Date値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static java.sql.Date toSqlDate(@Nullable String date, DateFormatType format) {
if (format == null) {
throw new IllegalArgumentException("formatパラメータはnullにできません。");
}
return toSqlDate(date, format.getFormatString());
}
/**
* 文字列をjava.sql.Timestamp値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static java.sql.Timestamp toSqlTimestamp(@Nullable String date, String format) {
Date d = toDate(date, format);
if (d == null) {
return null;
}
return new java.sql.Timestamp(d.getTime());
}
/**
* 文字列をjava.sql.Timestamp値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static java.sql.Timestamp toSqlTimestamp(@Nullable String date, DateFormatType format) {
if (format == null) {
throw new IllegalArgumentException("formatパラメータはnullにできません。");
}
return toSqlTimestamp(date, format.getFormatString());
}
/**
* Date値を文字列値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static String toString(@Nullable Date date, String format) {
if (date == null) {
return null;
}
return toString(date, format, Locale.getDefault());
}
/**
* Date値を文字列値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static String toString(@Nullable Date date, String format, Locale locale) {
if (date == null) {
return null;
}
return new SimpleDateFormat(format, locale).format(date);
}
/**
* Date値を文字列値に変換します。
* @param date
* @param format
* @return
*/
@Nullable
public static String toString(@Nullable Date date, DateFormatType format) {
if (format == null) {
throw new IllegalArgumentException("formatパラメータはnullにできません。");
}
return toString(date, format.getFormatString(), format.getFormatLocale());
}
/**
* 文字列をBigDecimal値に変換します。
* @param value
* @return
*/
@Nullable
public static BigDecimal toBigDecimal(@Nullable String value) {
if (!Strings.isNullOrEmpty(value)) {
try {
return new BigDecimal(value);
} catch (NumberFormatException e) {
}
}
return null;
}
/**
* BigDecimal値を文字列に変換します。
* @param value
* @return
*/
@Nullable
public static String toString(@Nullable BigDecimal value) {
return (value != null) ? value.toString() : null;
}
/**
* BigDecimal値を、roundで指定した丸め処理でスケール変換して文字列に変換します。
* @param value 値
* @param scale 有効桁数
* @param round 丸め処理の方法
* @return 文字列値
*/
@Nullable
public static String toString(@Nullable BigDecimal value, int scale, @Nonnull RoundingMode round) {
if (round == null) {
throw new IllegalArgumentException("roundパラメータはnullにできません。");
}
return (value != null) ? value.setScale(scale, round).toString() : null;
}
/**
* バイト配列をハイフンでつないだHEX文字列に変換します。
* バイト配列を文字列に変換する場合は、new String(bytes, encoding)を使ってください。
* @param bytes
* @return
*/
public static String toString(@Nonnull byte[] bytes) {
return toString(bytes, "-");
}
/**
* バイト配列をseparatorでつないだHEX文字列に変換します。
* バイト配列を文字列に変換する場合は、new String(bytes, encoding)を使ってください。
* @param bytes
* @return
*/
public static String toString(@Nonnull byte[] bytes, @Nonnull String separator) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (byte b : bytes) {
if (first) {
first = false;
}
else {
sb.append(separator);
}
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
package kobachi.util;
import java.util.Locale;
/**
* よくある日付フォーマット
*
*/
public enum DateFormatType {
/** yyyy/MM/dd */
YYYY_MM_DD("yyyy/MM/dd"),
/** yyyyMMdd */
YYYYMMDD("yyyyMMdd"),
/** yyyy/M/d */
YYYY_M_D("yyyy/M/d"),
/** yyyy/MM */
YYYY_MM("yyyy/MM"),
/** yyyy/M */
YYYY_M("yyyy/M"),
/** MM月dd日 */
MM_DD_JP("MM月dd日", Locale.JAPAN),
/** M月d日 */
M_D_JP("M月d日", Locale.JAPAN),
/** MM月dd日(曜日) */
MM_DD_E_JP("MM月dd日(E)", Locale.JAPAN),
/** M月d日(曜日) */
M_D_E_JP("M月d日(E)", Locale.JAPAN),
/** yyyy/MM/dd HH:mm */
YYYY_MM_DD_HH_MM("yyyy/MM/dd HH:mm"),
/** yyyy/MM/dd HH:mm:ss */
YYYY_MM_DD_HH_MM_SS("yyyy/MM/dd HH:mm:ss"),
/** HH:mm */
HH_MM("HH:mm"),
/** HHmm */
HHMM("HHmm"),
/** yyyy年M月 */
YYYY_M_JP("yyyy年M月", Locale.JAPAN),
/** yyyy年M月d日 */
YYYY_M_D_JP("yyyy年M月d日", Locale.JAPAN),
/** (年号)y年 */
NENGO_Y("GGGGyyyy年", Locale.JAPAN),
/** (年号)y年M月 */
NENGO_Y_M("GGGGyyyy年M月", Locale.JAPAN),
/** (年号)y年M月d日 */
NENGO_Y_M_D("GGGGyyyy年M月d日", Locale.JAPAN),
/** ISO 8601 Basic */
ISO8601_BASIC("yyyyMMdd'T'HHmmss.SSSZ"),
/** Solr */
SOLR("yyyy-MM-dd'T'HH:mm:ss'Z'"),
;
private final String formatString;
private final Locale locale;
private DateFormatType(String format) {
formatString = format;
locale = Locale.getDefault();
}
private DateFormatType(String format, Locale locale) {
formatString = format;
this.locale = locale;
}
/**
* 書式文字列を取得します
* @return
*/
public String getFormatString() {
return formatString;
}
/**
* フォーマット用ロケールを取得します。
* @return
*/
public Locale getFormatLocale() {
return locale;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment