Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Jan 30, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Time formatting

I need to find 2 things. I need a class that will allow me to take a date and add and subtract days/months/years from it.

I also need a class that will allow me to format strings of data. IE. a date a certain way either mm/dd/yyyy or mm-dd-yyyy or yyyy-mm-dd or any other way.

Any clue if these class types exist anywhere? Thanks.

The java.util.Calendar and java.text.SimpleDateFormat classes allow you to do exactly that, but they are only present in Java 1.1 and up. The Calendar class contains a method called add(int, int), which can be used to add or subtract (by adding negative values) time on a field by field basis to a time. The SimpleDateFormat class allows you to format the time into a string based on your particular display criteria. The following example prints the current date in two different formats, adds two days the date, and then prints the date again. You should read the API documentation for the Calendar, GregorianCalendar, DateFormat, and SimpleDateFormat classes for more detailed information on how to use the classes.

import java.util.*;
import java.text.*;

public final class CalendarExample {

  public static final void main(String[] args) {
    Date date;
    Calendar calendar;
    SimpleDateFormat formatter1, formatter2;

    calendar = Calendar.getInstance();
    formatter1 = new SimpleDateFormat("MM-dd-yyyy");
    formatter2 = new SimpleDateFormat("yyyy-MM-dd");

    date = calendar.getTime();
    System.out.println("Today\n" + formatter1.format(date) + "\n" +

    // Add two days to the date
    calendar.add(Calendar.DAY_OF_YEAR, 2);
    date = calendar.getTime();
    System.out.println("\nTwo days from now\n" + formatter1.format(date) + 
		       "\n" + formatter2.format(date));


DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date