Java DateUtil

 

Java DateUtil

package com.apollo89.java.util;

import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Vector;
 
public class DateUtil {
    public static String getDate2String(String date, String originFormat, String targetFormat, String locale) {
        SimpleDateFormat parser = new SimpleDateFormat(originFormat, new Locale(locale));
        ParsePosition pos = new ParsePosition(0);
        DateFormat df = new SimpleDateFormat(targetFormat);
        return df.format(parser.parse(date, pos));
    }
     
    public static String[] getDates(String startDay, String endDay) {
        Vector v = new Vector();
        v.addElement(startDay);
        Calendar cal = getCalendar();
        cal.setTime(string2Date(startDay));
 
        String nextDay = date2String(cal.getTime());
 
        while (!nextDay.equals(endDay)) {
            cal.add(Calendar.DATE, 1);
            nextDay = date2String(cal.getTime());
            v.addElement(nextDay);
        }
 
        String[] dates = new String[v.size()];
        v.copyInto(dates);
        return dates;
    }
 
    public static Calendar getCalendar() {
        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"), Locale.KOREA);
        cal.setTime(new Date());
        return cal;
    }
 
    public static Date string2Date(String s) {
        return string2Date(s, "yyyyMMdd");
    }
 
    public static Date string2Date(String s, String format) {
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        date = sdf.parse(s, new ParsePosition(0));
        return date;
    }
 
    public static String date2String(Date d) {
        return date2String(d, "yyyyMMdd");
    }
 
    public static String date2String(Date d, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(d);
    }
}

 

This entry was posted in Java/JSP, Util/Tools and tagged , . Bookmark the permalink.

댓글 남기기