Java Hour getHour(String dateString)

Here you can find the source of getHour(String dateString)

Description

get Hour

License

Open Source License

Declaration

public static int getHour(String dateString) 

Method Source Code

//package com.java2s;

import java.util.Calendar;

public class Main {

    public static int getHour(String dateString) {
        Calendar calendar = getCalendar(dateString);
        return calendar.get(Calendar.HOUR_OF_DAY);
    }/*  ww  w .j  a  v a2  s  .co m*/

    public static Calendar getCalendar(String dateString) {
        Calendar calendar = Calendar.getInstance();
        String[] items = dateString.split("[-| |:]");
        int len = items.length;
        if (len == 1) {
            String item = items[0];
            if (item.length() >= 4) {
                calendar.set(Calendar.YEAR, Integer.parseInt(item.substring(0, 4)));
            }
            if (item.length() >= 6) {
                calendar.set(Calendar.MONTH, Integer.parseInt(item.substring(4, 6)) - 1);
            }
            if (item.length() >= 8) {
                calendar.set(Calendar.DATE, Integer.parseInt(item.substring(6, 8)));
            }
            if (item.length() >= 10) {
                calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(item.substring(8, 10)));
            }
            if (item.length() >= 12) {
                calendar.set(Calendar.MINUTE, Integer.parseInt(item.substring(10, 12)));
            }
            if (item.length() >= 14) {
                calendar.set(Calendar.SECOND, Integer.parseInt(item.substring(12, 14)));
            }
        } else {
            if (len > 1) {
                calendar.set(Calendar.MONTH, Integer.parseInt(items[1]) - 1);
            } else {
                calendar.set(Calendar.MONTH, 0);
            }
            if (len > 2) {
                calendar.set(Calendar.DATE, Integer.parseInt(items[2]));
            } else {
                calendar.set(Calendar.DATE, 1);
            }
            if (len > 3) {
                calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(items[3]));
            } else {
                calendar.set(Calendar.HOUR_OF_DAY, 0);
            }
            if (len > 4) {
                calendar.set(Calendar.MINUTE, Integer.parseInt(items[4]));
            } else {
                calendar.set(Calendar.MINUTE, 0);
            }
            if (len > 5) {
                calendar.set(Calendar.SECOND, Integer.parseInt(items[5]));
            } else {
                calendar.set(Calendar.SECOND, 0);
            }
        }
        return calendar;
    }
}

Related

  1. getHour(Date date)
  2. getHour(Date now)
  3. getHour(final Date timeFrom)
  4. getHour(java.util.Date date)
  5. getHour(long t)
  6. getHour(String dateTime)
  7. getHour12(Date date)
  8. getHourAfter(Date date, int hour)
  9. getHourAfter(final Date _from, final int _hours)