【发布时间】:2010-04-08 10:36:15
【问题描述】:
有没有办法在 Java 中获取时间分隔符“:”?它是某处的常数还是吸气剂?也许有相当于 File.separator 的东西?
DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(date);返回我的时间字符串
在这种情况下,当以后有人想要解析这个字符串时,只使用 ':' 是否安全?
【问题讨论】:
有没有办法在 Java 中获取时间分隔符“:”?它是某处的常数还是吸气剂?也许有相当于 File.separator 的东西?
DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(date);返回我的时间字符串
在这种情况下,当以后有人想要解析这个字符串时,只使用 ':' 是否安全?
【问题讨论】:
我认为使用':' 是安全的。它在SimpleDateFormat 中硬编码。例如:
if (text.charAt(++pos.index) != ':')
【讨论】:
试试下面的
public static String getTimeSeparator(Locale locale) {
String sepValue = ":";
DateFormat dateFormatter = DateFormat.getTimeInstance(DateFormat.SHORT,
locale);
DateFormatSymbols dfs = new DateFormatSymbols(locale);
Date now = new Date();
String[] amPmStrings = dfs.getAmPmStrings();
String localeTime = dateFormatter.format(now);
//remove the am pm string if they exist
for (int i = 0; i < amPmStrings.length; i++) {
localeTime = localeTime.replace(dfs.getAmPmStrings()[i], "");
}
// search for the character that isn't a digit.
for (int currentIndex = 0; currentIndex < localeTime.length(); currentIndex++) {
if (!(Character.isDigit(localeTime.charAt(currentIndex))))
{
sepValue = localeTime.substring(currentIndex, currentIndex + 1);
break;
}
}
return sepValue;
}
【讨论】: