Cosmo Kramer
Cosmo Kramer

Reputation: 1

Incrementing date in yyyymmddhhmmss.mmm format in Java

I want to increment the milliseconds in any given date in the format yyyymmddhhmmss.mmm in each iteration. mmm here represents milliseconds. And I want to perfom this operation in Java 1.5.

For example: 20120823151034.567 should be incremented to 20120823151034.568

Upvotes: 0

Views: 17371

Answers (6)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

You can use Calendar Class as well as Date Class for this....

Date Class:

final String dateStr = "20120823151034.567";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");

Date date = format.parse(input);
date.setTime(date.getTime()+1);
System.out.println(format.format(date));

Calendar Class:

final String dateStr = "20120823151034.567";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");

Calendar c = Calendar.getInstance();
c.setTime(format.parse(dateStr ));
c.add(Calendar.MILLISECOND,1);
System.out.println(format.format(c.getTime()));

In both cases, format.parse() has the potential to throw a ParseException, which you will need to catch and handle.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533930

You can use long milli-seconds which make incrementing trivial.

final String input = "20120823151034.567";
final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss.SSS");

Date d = df.parse(input);
d.setTime(d.getTime()+1);
System.out.println(df.format(d));

I wouldn't use Calendar as its very slow.

Upvotes: 4

slim
slim

Reputation: 41271

An alternative without using Calendar (although, Calendar is fine)

 final String input = "20120814120000.111";
 final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");

 Date date = new format.parse(input);
 long time = date.getTime();

 Date incrementedDate = new Date(time + 1);
 System.out.println(format.format(date));

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200306

This gives you what you want. It will work across any day/month/year boundary, as well as handling the start and end of daylight saving time.

  final String input = "20120823151034.567";
  final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
  final Calendar c = Calendar.getInstance();
  c.setTime(df.parse(input));
  c.add(Calendar.MILLISECOND, 1);
  System.out.println(df.format(c.getTime()));

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

The best class to use for this operation is Calendar. You set it to the desired date, and then use

myCalendar.add(Calendar.MILLISECOND, 1);

to advance it by one millisecond. Use DateFormat to produce string representations.

Upvotes: 3

gkuzmin
gkuzmin

Reputation: 2484

You can parse String to Date object and use getTime() and setTime(long l) to modify date. Then you can convert Date object back to String. For parsing String and converting Date object back to String you can use SimpleDateFormat class.

Upvotes: 3

Related Questions