Dominic
Dominic

Reputation: 9

SimpleDateFormat Exception in Java

I am a beginner in programming.

I want my code to be formatted in this order dd-MM-yyyy.

If not throw an exception.

What do I need to do?

    public Date(int day, int month, int year) {
    this.Day = tag;
    this.Month = month;
    this.Year = year;
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    if (day != sdf) {

    }

Thank you so much for your help!

Upvotes: 0

Views: 62

Answers (2)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

It sounds like you should use the LocalDate class, which is the Java 8 way of storing a day month and year. And since you're asking about formatting, I guess you're interested in using a DateTimeFormatter and returning your value as a String.

public String formatDate(int day, int month, int year) {
    LocalDate theDate = LocalDate.of(year, month, day);
    DateTimeFormatter theFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    return theFormatter.format(theDate);
}

Upvotes: 3

user20184534
user20184534

Reputation: 41

This would be useful

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Date1 {
    public static void main(String args[]) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            Date strdate1 = sdf.parse("19-04-2018"); //target1 date
            Date strdate2 = sdf.parse("02-04-2017"); //target2 date
            if (strdate2.before(strdate1)) {
                System.out.println("not outdated");
            } else {
                System.out.println("outdated");
            }
        } catch(ParseException ex) {
            ex.printStackTrace();
        }
    }
}

Upvotes: 0

Related Questions