繁体   English   中英

替换特定位置中的子字符串

[英]Replace substring in a particular postion

String date = "2012-11-28 12:30:30";

我想通过使用String.replace方法将日期替换为2012-11-28 12:00:00

String replacedDate = date.replace(date.substring(14, 19), "00:00");

它工作正常,但如果日期是:

String date = "2012-11-28 18:18:18";

使用上面的方法,结果将是2012-11-28 00:00:28但我希望输出为2012-11-28 18:00:00

您不需要在此处使用String.replace方法。 如果您知道要替换的确切索引,并且您确定它们将始终相同,那么您可以使用子字符串和字符串连接:

String date = "2012-11-28 12:30:30";
date = date.substring(0, 14) + "00:00";

看到它在线工作: ideone

注意:如果您的字符串确实表示日期,请考虑使用Date类型的变量而不是String

您可以使用忽略分钟和秒的Date解析器,而不是直接操作字符串:

String s = "2012-11-28 12:30:30";
//skip the minutes, seconds
Date date = new SimpleDateFormat("yyyy-MM-dd HH").parse(s); 

String result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println("result = " + result);

奖励:如果日期不是预期的格式,您将获得有用的例外

这是一个约会/时间。 通过解析上述入合适的日期/时间对象并使用的日期/时间相关的方法操纵它把它作为这样 这样您就不必依赖substrig / regexp等,也不会冒着创建无效日期/时间参考的风险。

例如,使用SimpleDateFormatCalendar ,或使用Joda-Time获得更直观,更健壮的API。

目前,您有一个字符串式系统,而不是类型系统。

您也可以先要求第一个':'然后添加“00:00”

String date="2012-11-28 18:18:18";
int i = date.indexOf(':');
String format = date.substring(0,i+1) + "00:00";

我认为你的解决方案不起作用,因为replace方法有这个签名

public String replace(char oldChar, char newChar)

public String replace(String oldChar, String newChar)

这个答案是为了解问题,解决问题,考虑其他好的答案!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM