Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Shantanu Kumar

By: a guest on Oct 12th, 2009  |  syntax: Java  |  size: 2.14 KB  |  views: 172  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import java.text.DateFormat;
  2. import java.util.Arrays;
  3. import java.util.Calendar;
  4. import java.util.Date;
  5. import java.util.TimeZone;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class DateParse {
  10.    
  11.     public static void main(String[] args) throws Exception {
  12.         final String dateStr = "1997-02-14T00:00:00.0000000+05:30";
  13.        
  14.         final String metaChars = "$()*+.?[\\^{|"; // Java regex meta-characters
  15.        
  16.         final Pattern YMD_PATTERN = Pattern.compile(
  17.         "(\\d{4})[/\\-\\.](\\d{2})[/\\-\\.](\\d{2})"  // yyyy-mm-dd
  18.         + "T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{1,20})" // Thh:mm:ss.microsec
  19.         + "\\+(\\d{2}):(\\d{2})"                      // +th:tm (timezone)
  20.         );
  21.        
  22.         final Matcher matcher = YMD_PATTERN.matcher(dateStr);
  23.         if (matcher.matches()) {
  24.             final int TOKEN_COUNT = 9;
  25.             final String[] tokens = new String[TOKEN_COUNT];
  26.             for (int i = 0; i < TOKEN_COUNT; i++) {
  27.                 tokens[i] = matcher.group(i + 1);
  28.                 if (tokens[i] == null) {
  29.                     throw new IllegalStateException("Invalid date string - cannot parse");
  30.                 }
  31.             }
  32.             System.out.println("" + Arrays.asList(tokens));
  33.             // get time-zone
  34.             final String tzStr = "GMT+" + tokens[7] + ":" + tokens[8];
  35.             final TimeZone tz = TimeZone.getTimeZone(tzStr);
  36.             final Calendar cal = Calendar.getInstance(tz);
  37.            
  38.             final int y = Integer.parseInt(tokens[0]);
  39.             final int m = Integer.parseInt(tokens[1]);
  40.             final int d = Integer.parseInt(tokens[2]);
  41.             final int hh = Integer.parseInt(tokens[3]);
  42.             final int mm = Integer.parseInt(tokens[4]);
  43.             final int ss = Integer.parseInt(tokens[5]);
  44.             final int ms = Integer.parseInt(tokens[6]);
  45.             cal.set(y, m - 1 /* month is zero-based */, d, hh, mm, ss);
  46.            
  47.             final Date date = cal.getTime();
  48.             System.out.println(date);
  49.         } else {
  50.             System.out.println("Does not match");
  51.         }
  52.     }
  53. }