java字符串 删除指定字符的那些事

需求如下:

1.算出2周以前的时间,以正常日期格式返回

2.如果月份和日期前面有0需要去掉返回结果,比如:2017-08-15  就需要显示2017-8-15。

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -14);
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(date);//这里输出的日期就是2周前的日期,输出为2017-08-16

第一种方法:

String result = "";

for(int i = 0; i< time.length(); i++){

  if ((i == 5 && time.charAt(i) == '0') | (i == 8 && time.charAt(i) == '0')){

    index += "";

  } else {

    index += time.charAt(i);

  }

}

system.out,printn(result);

第二种方法(最简单的方法,使用StringBuffer就Ok):

StringBuffer buffer = new StringBuffer(time);
if (buffer.charAt(5) == '0') {
  buffer.deleteCharAt(5);
}
if (buffer.charAt(7) == '0') {
  buffer.deleteCharAt(7);
}
System.out.println(buffer.toString());

原文地址:https://www.cnblogs.com/lyh1299259684/p/7451356.html