Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
BEGIN LICENSE BLOCK ***** Version: EPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Eclipse Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.eclipse.org/legal/epl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2002, 2009 Jan Arne Petersen <jpetersen@uni-bonn.de> Copyright (C) 2004 Charles O Nutter <headius@headius.com> Copyright (C) 2004 Anders Bengtsson <ndrsbngtssn@yahoo.se> Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the EPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the EPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 package org.jruby.util;
 
 import java.util.Date;
 import java.util.List;
 
 
 import static org.jruby.util.RubyDateFormat.FieldType.*;
 
 public class RubyDateFormat extends DateFormat {
     private static final long serialVersionUID = -250429218019023997L;
 
     private boolean ruby_1_9;
     private List<TokencompiledPattern;
 
     private final DateFormatSymbols formatSymbols;

    
raw string, no formatting
 
     private static final int FORMAT_STRING = 0;
    
%A
 
     private static final int FORMAT_WEEK_LONG = 1;
    
%a
 
     private static final int FORMAT_WEEK_SHORT = 2;
    
%B
 
     private static final int FORMAT_MONTH_LONG = 3;
    
%b, %h
 
     private static final int FORMAT_MONTH_SHORT = 4;
    
%d
 
     private static final int FORMAT_DAY = 5;
    
%e
 
     private static final int FORMAT_DAY_S = 6;
    
%H
 
     private static final int FORMAT_HOUR = 7;
    
%I
 
     private static final int FORMAT_HOUR_M = 8;
    
%l
 
     private static final int FORMAT_HOUR_S = 9;
    
%j
 
     private static final int FORMAT_DAY_YEAR = 10;
    
%M
 
     private static final int FORMAT_MINUTES = 11;
    
%m
 
     private static final int FORMAT_MONTH = 12;
    
%p
 
     private static final int FORMAT_MERIDIAN = 13;
    
%P
 
     private static final int FORMAT_MERIDIAN_LOWER_CASE = 14;
    
%S
 
     private static final int FORMAT_SECONDS = 15;
    
%U
 
     private static final int FORMAT_WEEK_YEAR_S = 16;
    
%W
 
     private static final int FORMAT_WEEK_YEAR_M = 17;
    
%w
 
     private static final int FORMAT_DAY_WEEK = 18;
    
%Y
 
     private static final int FORMAT_YEAR_LONG = 19;
    
%y
 
    private static final int FORMAT_YEAR_SHORT = 20;
    
%z, %:z, %::z, %:::z
    private static final int FORMAT_COLON_ZONE_OFF = 21;
    
%Z
    private static final int FORMAT_ZONE_ID = 22;
    
%C
    private static final int FORMAT_CENTURY = 23;
    
%k
    private static final int FORMAT_HOUR_BLANK = 24;
    
%L
    private static final int FORMAT_MILLISEC = 25;
    
%s
    private static final int FORMAT_EPOCH = 26;
    
%u
    private static final int FORMAT_DAY_WEEK2 = 27;
    
%V
    private static final int FORMAT_WEEK_WEEKYEAR = 28;
    
%N
    private static final int FORMAT_NANOSEC = 29;
    
%G
    private static final int FORMAT_WEEKYEAR = 30;
    
formatter
    private static final int FORMAT_OUTPUT = 31;
    
%g
    private static final int FORMAT_WEEKYEAR_SHORT = 32;
    /* Only for Date/DateTime from here */
    
%Q
    private static final int FORMAT_MICROSEC_EPOCH = 33;
    
%+
    private static final int FORMAT_DATE_1 = 34;
    private static class Token {
        private final int format;
        private final Object data;
        
        public Token(int format) {
            this(formatnull);
        }
        public Token(int formatObject data) {
            this. = format;
            this. = data;
        }
        
        
Gets the data.

Returns:
Returns a Object
        public Object getData() {
            return ;
        }

        
Gets the format.

Returns:
Returns a int
        public int getFormat() {
            return ;
        }
    }

    
Constructor for RubyDateFormat.
    public RubyDateFormat() {
        this(""new DateFormatSymbols());
    }
    public RubyDateFormat(String patternLocale aLocale) {
        this(patternnew DateFormatSymbols(aLocale));
    }
    public RubyDateFormat(String patternLocale aLocaleboolean ruby_1_9) {
        this(patternaLocale);
        this. = ruby_1_9;
    }
    
    public RubyDateFormat(String patternDateFormatSymbols formatSymbols) {
        super();
        this. = formatSymbols;
        applyPattern(pattern);
    }
    
    public void applyPattern(String pattern) {
        applyPattern(patternfalse);
    }
    
    public void applyPattern(String patternboolean dateLibrary) {
        compilePattern(patterndateLibrary);
    }
    private void compilePattern(String patternboolean dateLibrary) {
         = new LinkedList<Token>();
        
        int len = pattern.length();
        boolean ignoredModifier = false;
        char next;
        for (int i = 0; i < len;) {
            if (pattern.charAt(i) == '%' || (ignoredModifier && !(ignoredModifier = false))) {
                i++;
                if (i == len) {
                    .add(new Token("%"));
                } else {
                    i = addOutputFormatter(patterni);
                    switch (pattern.charAt(i)) {
                    case 'A' :
                        .add(new Token());
                        break;
                    case 'a' :
                        .add(new Token());
                        break;
                    case 'B' :
                        .add(new Token());
                        break;
                    case 'b' :
                    case 'h' :
                        .add(new Token());
                        break;
                    case 'C' :
                        .add(new Token());
                        break;
                    case 'c' :
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        break;
                    case 'D':
                        .add(new Token());
                        .add(new Token("/"));
                        .add(new Token());
                        .add(new Token("/"));
                        .add(new Token());
                        break;
                    case 'd':
                        .add(new Token());
                        break;
                    case 'E':
                        next = '\0';
                        if (i + 1 < len)
                            next = pattern.charAt(i+1);
                        switch (next) {
                            case 'c'case 'C'case 'x'case 'X'case 'y'case 'Y':
                                ignoredModifier = true;
                                i--;
                                break;
                            default:
                                .add(new Token("%E"));
                                break;
                        }
                        break;
                    case 'e':
                        .add(new Token());
                        break;
                    case 'F':
                        .add(new Token());
                        .add(new Token("-"));
                        .add(new Token());
                        .add(new Token("-"));
                        .add(new Token());
                        break;
                    case 'G':
                        .add(new Token());
                        break;
                    case 'g':
                        .add(new Token());
                        break;
                    case 'H':
                        .add(new Token());
                        break;
                    case 'I':
                        .add(new Token());
                        break;
                    case 'j':
                        .add(new Token());
                        break;
                    case 'k':
                        .add(new Token());
                        break;
                    case 'L':
                        .add(new Token());
                        break;
                    case 'l':
                        .add(new Token());
                        break;
                    case 'M':
                        .add(new Token());
                        break;
                    case 'm':
                        .add(new Token());
                        break;
                    case 'N':
                        .add(new Token());
                        break;
                    case 'n':
                        .add(new Token("\n"));
                        break;
                    case 'O':
                        next = '\0';
                        if (i + 1 < len)
                            next = pattern.charAt(i+1);
                        switch (next) {
                            case 'd'case 'e'case 'H'case 'k'case 'I'case 'l'case 'm':
                            case 'M'case 'S'case 'u'case 'U'case 'V'case 'w'case 'W':
                            case 'y':
                                ignoredModifier = true;
                                i--;
                                break;
                            default:
                                .add(new Token("%O"));
                                break;
                        }
                        break;
                    case 'p':
                        .add(new Token());
                        break;
                    case 'P':
                        .add(new Token());
                        break;
                    case 'Q':
                        if (dateLibrary)
                            .add(new Token());
                        else
                            .add(new Token("%Q"));
                        break;
                    case 'R':
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        break;
                    case 'r':
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        break;
                    case 's':
                        .add(new Token());
                        break;
                    case 'S':
                        .add(new Token());
                        break;
                    case 'T':
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        break;
                    case 't':
                        .add(new Token(,"\t"));
                        break;
                    case 'u':
                        .add(new Token());
                        break;
                    case 'U':
                        .add(new Token());
                        break;
                    case 'v':
                        .add(new Token());
                        .add(new Token("-"));
                        if (!dateLibrary)
                            .add(new Token(new TimeOutputFormatter("^", 0)));
                        .add(new Token());
                        .add(new Token("-"));
                        .add(new Token());
                        break;
                    case 'V':
                        .add(new Token());
                        break;
                    case 'W':
                        .add(new Token());
                        break;
                    case 'w':
                        .add(new Token());
                        break;
                    case 'X':
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        break;
                    case 'x':
                        .add(new Token());
                        .add(new Token("/"));
                        .add(new Token());
                        .add(new Token("/"));
                        .add(new Token());
                        break;
                    case 'Y':
                        .add(new Token());
                        break;
                    case 'y':
                        .add(new Token());
                        break;
                    case 'Z':
                        if (dateLibrary) {
                            // +HH:MM in 'date', never zone name
                            .add(new Token(new TimeOutputFormatter(":", 0)));
                            .add(new Token());
                        } else {
                            .add(new Token());
                        }
                        break;
                    case 'z':
                        .add(new Token());
                        break;
                    case '+':
                        if (!dateLibrary) {
                            .add(new Token("%+"));
                            break;
                        }
                        // %a %b %e %H:%M:%S %Z %Y
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(":"));
                        .add(new Token());
                        .add(new Token(" "));
                        // %Z: +HH:MM in 'date', never zone name
                        .add(new Token(new TimeOutputFormatter(":", 0)));
                        .add(new Token());
                        .add(new Token(" "));
                        .add(new Token());
                        break;
                    case '%':
                        .add(new Token("%"));
                        break;
                    default:
                        .add(new Token("%" + pattern.charAt(i)));
                    }
                    i++;
                }
            } else {
                StringBuilder sb = new StringBuilder();
                for (;i < len && pattern.charAt(i) != '%'i++) {
                    sb.append(pattern.charAt(i));
                }
                .add(new Token(sb.toString()));
            }
        }
    }
    private int addOutputFormatter(String patternint index) {
        TimeOutputFormatter outputFormatter = TimeOutputFormatter.getFormatter(pattern.substring(index - 1));
        if (outputFormatter != null) {
            index += outputFormatter.getFormat().length();
            .add(new Token(outputFormatter));
        }
        return index;
    }
    private DateTime dt;
    private long nsec;
    public void setDateTime(final DateTime dt) {
        this. = dt;
    }
    public void setNSec(long nsec) {
        this. = nsec;
    }
    static enum FieldType {
        NUMERIC('0', 0),
        NUMERIC2('0', 2),
        NUMERIC2BLANK(' ', 2),
        NUMERIC3('0', 3),
        NUMERIC4('0', 4),
        NUMERIC5('0', 5),
        TEXT(' ', 0);
        char defaultPadder;
        int defaultWidth;
        FieldType(char padderint width) {
             = padder;
             = width;
        }
    }

    
    public StringBuffer format(Date ignoredStringBuffer toAppendToFieldPosition fieldPosition) {
        for (Token token) {
            String output = null;
            long value = 0;
            FieldType type = ;
            int format = token.getFormat();
            switch (format) {
                case :
                    formatter = (TimeOutputFormattertoken.getData();
                    continue// go to next token
                case :
                    output = token.getData().toString();
                    break;
                case :
                    // This is GROSS, but Java API's aren't ISO 8601 compliant at all
                    int v = (.getDayOfWeek()+1)%8;
                    if(v == 0) {
                        v++;
                    }
                    output = .getWeekdays()[v];
                    break;
                case :
                    // This is GROSS, but Java API's aren't ISO 8601 compliant at all
                    v = (.getDayOfWeek()+1)%8;
                    if(v == 0) {
                        v++;
                    }
                    output = .getShortWeekdays()[v];
                    break;
                case :
                    output = .getMonths()[.getMonthOfYear()-1];
                    break;
                case :
                    output = .getShortMonths()[.getMonthOfYear()-1];
                    break;
                case :
                    type = ;
                    value = .getDayOfMonth();
                    break;
                case :
                    type = ;
                    value = .getDayOfMonth();
                    break;
                case :
                    type = ;
                    value = .getHourOfDay();
                    break;
                case :
                    type = ;
                    value = .getHourOfDay();
                    break;
                case :
                case :
                    value = .getHourOfDay();
                    if (value == 0) {
                        value = 12;
                    } else if (value > 12) {
                        value -= 12;
                    }
                    type = (format == ) ?  : ;
                    break;
                case :
                    type = ;
                    value = .getDayOfYear();
                    break;
                case :
                    type = ;
                    value = .getMinuteOfHour();
                    break;
                case :
                    type = ;
                    value = .getMonthOfYear();
                    break;
                case :
                    output = .getHourOfDay() < 12 ? "AM" : "PM";
                    break;
                case :
                    output = .getHourOfDay() < 12 ? "am" : "pm";
                    break;
                case :
                    type = ;
                    value = .getSecondOfMinute();
                    break;
                case :
                    type = ;
                    value = formatWeekYear(...);
                    break;
                case :
                    type = ;
                    value = formatWeekYear(...);
                    break;
                case :
                    type = ;
                    value = .getDayOfWeek() % 7;
                    break;
                case :
                    type = ;
                    value = .getDayOfWeek();
                    break;
                case :
                    value = year(.getYear());
                    type = (value >= 0) ?  : ;
                    break;
                case :
                    type = ;
                    value = year(.getYear()) % 100;
                    break;
                case :
                    // custom logic because this is so weird
                    value = .getZone().getOffset(.getMillis()) / 1000;
                    int colons = formatter.getNumberOfColons();
                    output = formatZone(colons, (intvalueformatter);
                    break;
                case :
                    output = .getZone().getShortName(.getMillis());
                    break;
                case :
                    type = ;
                    value = year(.getYear()) / 100;
                    break;
                case :
                    type = ;
                    value = .getMillis() / 1000;
                    break;
                case :
                    type = ;
                    value = .getWeekOfWeekyear();
                    break;
                case :
                case :
                    value = .getMillisOfSecond() * 1000000;
                    if (value += ;
                    output = TimeOutputFormatter.formatNumber(value, 9, '0');
                    int defaultWidth = (format == ) ? 9 : 3;
                    int width = formatter.getWidth(defaultWidth);
                    if (width < 9) {
                        output = output.substring(0, width);
                    } else {
                        while(output.length() < width)
                            output += "0";
                    }
                    formatter = .// no more formatting
                    break;
                case :
                    value = year(.getWeekyear());
                    type = (value >= 0) ?  : ;
                    break;
                case :
                    type = ;
                    value = year(.getWeekyear()) % 100;
                    break;
                case :
                    // only available for Date
                    type = ;
                    value = .getMillis();
                    break;
            }
            output = formatter.format(outputvaluetype);
            // reset formatter
            formatter = .;
            toAppendTo.append(output);
        }
        return toAppendTo;
    }

    
Ruby always follows Astronomical year numbering, that is BC x is -x+1 and there is a year 0 (BC 1) but Joda-time returns -x for year x BC in Julian chronology (no year 0)
    private int year(int year) {
        Chronology c;
        if (year < 0 && (
                (c = .getChronology()) instanceof JulianChronology ||
                (c instanceof GJChronology && ((GJChronologyc).getGregorianCutover().isAfter())))
            return year + 1;
        return year;
    }
    private int formatWeekYear(int firstDayOfWeek) {
        java.util.Calendar dtCalendar = .toGregorianCalendar();
        dtCalendar.setFirstDayOfWeek(firstDayOfWeek);
        dtCalendar.setMinimalDaysInFirstWeek(7);
        int value = dtCalendar.get(...);
        if ((value == 52 || value == 53) &&
                (dtCalendar.get(.) == . )) {
            // MRI behavior: Week values are monotonous.
            // So, weeks that effectively belong to previous year,
            // will get the value of 0, not 52 or 53, as in Java.
            value = 0;
        }
        return value;
    }
    private String formatZone(int colonsint valueTimeOutputFormatter formatter) {
        int seconds = Math.abs(value);
        int hours = seconds / 3600;
        seconds %= 3600;
        int minutes = seconds / 60;
        seconds %= 60;
        if (value < 0 && hours != 0) { // see below when hours == 0
            hours = -hours;
        }
        String mm = TimeOutputFormatter.formatNumber(minutes, 2, '0');
        String ss = TimeOutputFormatter.formatNumber(seconds, 2, '0');
        char padder = formatter.getPadder('0');
        int defaultWidth = -1;
        String after = null;
        switch (colons) {
            case 0: // %z -> +hhmm
                defaultWidth = 5;
                after = mm;
                break;
            case 1: // %:z -> +hh:mm
                defaultWidth = 6;
                after = ":" + mm;
                break;
            case 2: // %::z -> +hh:mm:ss
                defaultWidth = 9;
                after = ":" + mm + ":" + ss;
                break;
            case 3: // %:::z -> +hh[:mm[:ss]]
                if (minutes == 0) {
                    if (seconds == 0) { // +hh
                        defaultWidth = 3;
                        after = "";
                    } else { // +hh:mm
                        return formatZone(1, valueformatter);
                    }
                } else { // +hh:mm:ss
                    return formatZone(2, valueformatter);
                }
                break;
        }
        int minWidth = defaultWidth - 1;
        int width = formatter.getWidth(defaultWidth);
        if (width < minWidth) {
            width = minWidth;
        }
        width -= after.length();
        String before = TimeOutputFormatter.formatSignedNumber(hourswidthpadder);
        if (value < 0 && hours == 0) // the formatter could not handle this case
            before = before.replace('+''-');
        return before + after;
    }

    
    public Date parse(String sourceParsePosition pos) {
        throw new UnsupportedOperationException();
    }
New to GrepCode? Check out our FAQ X