java字串 刪除指定字元的那些事

來源:互聯網
上載者:User

標籤:form   calendar   輸出   日期格式   time   stringbu   ++   去掉   index   

公司突然有這麽這需求:

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());

java字串 刪除指定字元的那些事

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.