Mike Kucera
Mike Kucera

Reputation: 2072

How to format a String with multiple dates in Java

I would like to format a String that contains patterns for more than one date/time. For example:

'Starting on' EEEE 'at' h:mm a 'and ending on' MMM d

Here I am trying to use two dates in the same format string, a start date and an end date. I don't want to split it into two strings because the ordering and structure of the sentence might be different in other languages and I don't want to put any assumptions into my code. As far as I can tell this can't be done with SimpleDateFormat as the format() methods only take one date object.

Upvotes: 1

Views: 394

Answers (2)

Ray Stojonic
Ray Stojonic

Reputation: 1270

See http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#dt, for example:

    Date today = new Date();
    Date yesterday = new Date();
    yesterday.setTime(today.getTime() - (1000*60*60*24) );
    System.out.printf( "Yesterday was: %ta, today is: %ta%n ", yesterday, today );

Output

    Yesterday was: Thu, today is: Fri

Upvotes: 1

user1697575
user1697575

Reputation: 2848

You can use java.text.MessageFormat that has ways to provide data format you need.

String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     arguments);

Upvotes: 3

Related Questions