如何在Java中用零填充字符串?

时间:2019-07-11 10:18:00

标签: java string padding

根据要求,我想根据以下格式获得唯一的参考。

参考应为= 15个字符 日期格式(yyyy-MM--dd)+ ZERO`s + ID; 例1 = 201911070000181 例如2 = 201911070000090

在代码示例中,我将日期显示为字符串,将ID显示为字符串,有人可以在这里帮助我吗? 谢谢。

Date today = Utils.getCurrentDateByTimeZone(environment.getProperty(TIME_ZONE));
    String pattern = "yyyyMMdd";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
    String date = simpleDateFormat.format(today);
    String merchantId = String.valueOf(transactionData.getMerchant().getMerchantId());

2 个答案:

答案 0 :(得分:2)

您可以使用String格式执行此操作。

String.format("%s%07d", date, id);
// if date="20191107" and id=181, this will give 201911070000181

此代码的作用是,它将id之前的0附加到其长度为7之前。(第一部分是日期,我假设日期始终是8个字符长。)如果id是字符串,它将不起作用,所以我建议将其强制转换为整数。

答案 1 :(得分:1)

您始终可以使用StringBuilder

StringBuilder sb = new StringBuilder(15);
sb.append(date);
for (int i = date.length() ; i < 15 - merchantId.length(); i++) {
    sb.append('0');
}
sb.append (merchantId);
String reference = sb.toString();