Java - Gregorian Calender in variabe?

null.ts :

im having a hard time trying to change this print statement into a variable for comparing with other variables.

Is there a way to store the output as a variable instead of printing incase you need to determine the difference of two dates?

import java.util.GregorianCalendar;
import java.util.Calendar;

public class Test {

public static void main(String[] args){

int Day = 8;
int Month = 2;
int Year = 1950;

    GregorianCalendar gcal = new GregorianCalendar(Year, Month, Day);

    String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; 

    System.out.println(month[gcal.get(Calendar.MONTH)] + " " + gcal.get(Calendar.DATE) + ", " 
            + gcal.get(Calendar.YEAR));}
}

This output prints: Mar 8, 1950

Andreas :

To store as a variable, so it can be compared to other dates, call getTime():

int Day = 8;
int Month = 2;
int Year = 1950;
GregorianCalendar gcal = new GregorianCalendar(Year, Month, Day);
Date date = gcal.getTime();

To format that as Mar 8, 1950, use a SimpleDateFormat:

SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy", Locale.US);
String str = dateFormat.format(date);

No need to make your own month names.


However, if you're using Java 8 or later1, you should use the LocalDate class instead of GregorianCalendar:

int day = 8;
int month = 3;
int year = 1950;
LocalDate date = LocalDate.of(year, month, day);

Note that unlike GregorianCalendar, the month value is 1-based, so it needs to be 3 to get Mar.

To format that as Mar 8, 1950, use a DateTimeFormatter:

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MMM d, uuuu", Locale.US);
String str = date.format(dateFormat);

1) If you're using Java 6 or 7, you can still use LocalDate by adding the ThreeTen-Backport library.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403861&siteId=1