我需要将日期格式化为特定的字符串。
我使用SimpleDateFormat
类使用模式“yyyy-MM-dd'T'HH:mm:ssZ
”格式化日期,它返回当前日期为
“2013-01-04T15:51:45+0530
”但我需要
“2013-01-04T15:51:45+05:30
”。
以下是使用的编码,
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
Log.e(C.TAG, "formatted string: "+sdf.format(c.getTime()));
输出:格式化字符串:2013-01-04T15:51:45+0530
我需要格式为2013-01-04T15:51:45+05:30
只需在gmt时间之间添加冒号。
因为我正在使用Google日历来插入活动,所以它只接受我提到的所需格式。
您也可以在模式中使用“ZZZZZ”代替“Z”(根据documentation)。像这样的东西
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.ENGLISH);
Log.e(C.TAG, "formatted string: "+sdf.format(c.getTime()));
你可以做的只是使用substring()手动添加“:”。我早些时候已经面对过这个问题了。
为什么不用regexp手动完成呢?
String oldDate = "2013-01-04T15:51:45+0530";
String newDate = oldDate.replaceAll("(\\+\\d\\d)(\\d\\d)", "$1:$2");
相同的结果,使用子字符串(如果性能是一个问题)。
String oldDate = "2013-01-04T15:51:45+0530";
int length = oldDate.length();
String newDate = oldDate.substring(0, length - 2) + ':' + oldDate.substring(length - 2);
试试这个
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
System.out.println("formatted string: "+sdf.format(c.getTime()));
String text = sdf.format(c.getTime());
String result = text.substring(0, 22) + ":" + text.substring(22);
System.out.println("result = " + result);
试试这个代码
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z", Locale.ENGLISH);
String s = sdf.format(c.getTime());
String fDate = s.substring(0, s.length()-2) +":"+s.substring(s.length()-2, s.length());
Log.e("check", "formatted string: "+fDate);
只需重构此代码并将“Locale.getDefault()”替换为您需要的Locale
private SimpleDateFormat getDateFormat() {
SimpleDateFormat dateFormat = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.DEFAULT, Locale.getDefault());
String pattern = dateFormat.toLocalizedPattern();
pattern = pattern.trim();
dateFormat.applyLocalizedPattern(pattern);
return dateFormat;
}
//这是用法
SimpleDateFormat sdf = getDateFormat();
sdf.format(new Date());
如果你想要一个不同时区的日期(标题建议)
val nowMillsUTC = System.currentTimeMillis()
val timeZoneID = "Australia/Perth"
val tz = TimeZone.getTimeZone(timeZoneID)
val simpleDateFormat = SimpleDateFormat("HH.mm dd.MMM.yyyy", Locale.getDefault())
simpleDateFormat.setTimeZone(tz)
val resultTxt = simpleDateFormat.format(nowMillsUTC)
print(timeZoneID + " -> " + resultTxt)
// Australia/Perth -> 19.59 21.Mar.2019