devxlogo

Time formatting

Time formatting

Question:
I need to find 2 things. I need a classthat will allow me to take a date and addand subtract days/months/years from it.

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

Any clue if these class types exist anywhere?Thanks.

Answer:
The java.util.Calendar and java.text.SimpleDateFormat classes allow youto 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 beused to add or subtract (by adding negative values) time on a field byfield basis to a time. The SimpleDateFormat class allows you to formatthe time into a string based on your particular display criteria. Thefollowing example prints the current date in two different formats, addstwo days the date, and then prints the date again. You should read theAPI documentation for the Calendar, GregorianCalendar, DateFormat, andSimpleDateFormat classes for more detailed information on how to use theclasses.

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
" + formatter1.format(date) + "
" +		       formatter2.format(date));    // Add two days to the date    calendar.add(Calendar.DAY_OF_YEAR, 2);    date = calendar.getTime();    System.out.println("
Two days from now
" + formatter1.format(date) + 		       "
" + formatter2.format(date));  }}

devx-admin

Share the Post: