Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * @param dateString
     * @return a java Date object that correspond to the dateString
     * Convert the dateString to a Date object
     */
    public static Date getDateFromString(String dateString) {
        // The Irish Time: "Mon, 15 Apr 2013 06:55:14 +0000"
        // Guardian / BBC: Wed, 17 Apr 2013 12:57:50 GMT

        String[] elements = dateString.split("[:\\s+]");
        int year = Integer.parseInt(elements[3]);
        int month = getMonth(elements[2].toLowerCase());
        int date = Integer.parseInt(elements[1]);
        int hour = Integer.parseInt(elements[4]);
        int minute = Integer.parseInt(elements[5]);
        int second = Integer.parseInt(elements[6]);

        Calendar cal = Calendar.getInstance();
        cal.set(year, month, date, hour, minute, second);

        return cal.getTime();
    }

    public static int getMonth(String str) {
        if (str.equals("jan"))
            return Calendar.JANUARY;
        if (str.equals("feb"))
            return Calendar.FEBRUARY;
        if (str.equals("mar"))
            return Calendar.MARCH;
        if (str.equals("apr"))
            return Calendar.APRIL;
        if (str.equals("may"))
            return Calendar.MAY;
        if (str.equals("jun"))
            return Calendar.JUNE;
        if (str.equals("jul"))
            return Calendar.JULY;
        if (str.equals("aug"))
            return Calendar.AUGUST;
        if (str.equals("sep"))
            return Calendar.SEPTEMBER;
        if (str.equals("oct"))
            return Calendar.OCTOBER;
        if (str.equals("nov"))
            return Calendar.NOVEMBER;
        if (str.equals("dec"))
            return Calendar.DECEMBER;

        return -1;
    }
}