简体   繁体   English

在Java中为大字符串添加前导零

[英]Adding a leading zero to a large string in Java

I am currently making an auction program in Java, I am trying to work out deadlines, however my date keeps coming out as (7/04/2013 11:22), is there a way to use String.format to add a leading zero to this date when it is a one digit day? 我目前正在用Java开发拍卖程序,我正在尝试确定截止日期,但是我的日期不断出现,因为(7/04/2013 11:22),有没有办法使用String.format添加前导零到今天是一位数字的日子?

String timeOne = Server.getDateTime(itemArray.get(1).time).toString()

It causes me a problem later on when I try to sub string it, and it is less than 17 characters long. 稍后当我尝试对它进行子字符串处理时,这会导致我遇到问题,并且它的长度少于17个字符。

Thanks in advance, James. 预先感谢詹姆斯。

@Leonard Brünings answer is the right way. @LeonardBrünings的答案是正确的方法。 And here's why your original code is the wrong way ... even if it worked. 这就是为什么您的原始代码使用错误的方式的原因……即使它起作用了。

The javadoc for Calendar.toString() says this: Calendar.toString()的Javadoc这样说:

" Return a string representation of this calendar. This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations. " 返回此日历的字符串表示形式。此方法仅用于调试目的,并且不同实现之间返回的字符串格式可能会有所不同。

Basically you are using toString() for a purpose that the javadoc says you shouldn't. 基本上,您使用toString()的目的是javadoc认为您不应该这样做的。 Even if you tweaked the output from toString() , the chances are that your code would be fragile. 即使您调整了toString()的输出,也有可能您的代码很脆弱。 A change in JVM could break it. JVM的更改可能会破坏它。 A change of locale could break it. 更改语言环境可能会破坏它。

Simply use the SimpleDateFormat 只需使用SimpleDateFormat

import java.text.SimpleDateFormat;

Calendar timeOne = Server.getDateTime(itemArray.get(1).time)

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm")

System.out.println(sdf.format(timeOne.getTime()))

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

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