Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    private static final String DEFAULT_DATE_REGEX = "\\b\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-2])\\b";

    /**
     * Parses a date from a String on the format YYYY-MM-DD.
     *
     * @param dateString the String to parse.
     * @return a Date based on the given String.
     */
    public static Date getMediumDate(String dateString) {
        try {
            final SimpleDateFormat format = new SimpleDateFormat();

            format.applyPattern(DEFAULT_DATE_FORMAT);

            return dateString != null && dateIsValid(dateString) ? format.parse(dateString) : null;
        } catch (ParseException ex) {
            throw new RuntimeException("Failed to parse medium date", ex);
        }
    }

    /**
     * This method checks whether the String inDate is a valid date following
     * the format "yyyy-MM-dd".
     *
     * @param dateString the string to be checked.
     * @return true/false depending on whether the string is a date according to the format "yyyy-MM-dd".
     */
    public static boolean dateIsValid(String dateString) {
        return dateString.matches(DEFAULT_DATE_REGEX);
    }
}