开发者

converting a calendar date to a string?

I am trying to get the program to call up the current date, add 30 days to it, and then out put that date as a string开发者_如何学Go.

        // Set calendar for due date on invoice gui
    Calendar cal = Calendar.getInstance();

    // Add 30 days to the calendar for the due date
    cal.add(Calendar.DATE, 30);
    Date dueDate = cal.getTime();
    dueDatestr = Calendar.toString(dueDate);


And the question is?

If you want to format your date, I suggest looking at java.text.SimpleDateFormat instead of using toString(). You can do something like:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
dueDateStr = dateFormat.format(dueDate); // renders as 11/29/2009


You almost have it:

Date dueDate = cal.getTime();
String dueDateAsString = dueDate.toString();

or

String dueDateAsFormattedString = DateFormat.format(dueDate);


You might want to consider using FastDateFormat from Apache commons, instead of SimpleDateFormat, because SimpleDateFormat is not thread safe.

FastDateFormat dateFormat = FastDateFormat.getInstance("MM/dd/yyyy");
dueDateStr = dateFormat.format(dueDate);

This is especially true if you wanted to use a static instance of the date formatter, which is a common temptation.


You can do it easily with a class of mine: https://github.com/knyttl/Maite/wiki/Maite-Date-and-Time

new Time()
    .plus(1, Time.DAY)
    .format("yyyy-MM-dd");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜