Java by API/java.text/ParsePosition — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 17:43, 31 мая 2010

new ParsePosition(int index)

       
/*
 Output: 
 
 on Tue Oct 01 00:00:00 PDT 2013 in  Vancouver, B.C.
 on Sun Mar 01 00:00:00 PST 1248 in  Ottawa, ON
 on Mon Jun 06 00:00:00 PST 1323 in  Toronto, ON
*/       
       
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainClass {
  public static void main(String[] a) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String input[] = { "2013-10-01 Vancouver, B.C.", 
                       "1248-03-01 Ottawa, ON",
                       "1323-06-06 Toronto, ON" };
    for (int i = 0; i < input.length; i++) {
      ParsePosition pp = new ParsePosition(0);
      Date d = formatter.parse(input[i], pp);
      if (d == null) {
        System.err.println("Invalid date in " + input[i]);
        continue;
      }
      String location = input[i].substring(pp.getIndex());
      System.out.println(" on " + d + " in " + location);
    }
  }
}





ParsePosition: getIndex()

       
/*
 Output: 
 
 on Tue Oct 01 00:00:00 PDT 2013 in  Vancouver, B.C.
 on Sun Mar 01 00:00:00 PST 1248 in  Ottawa, ON
 on Mon Jun 06 00:00:00 PST 1323 in  Toronto, ON
*/       
       
       
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainClass {
  public static void main(String[] a) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String input[] = { "2013-10-01 Vancouver, B.C.", 
                       "1248-03-01 Ottawa, ON",
                       "1323-06-06 Toronto, ON" };
    for (int i = 0; i < input.length; i++) {
      ParsePosition pp = new ParsePosition(0);
      Date d = formatter.parse(input[i], pp);
      if (d == null) {
        System.err.println("Invalid date in " + input[i]);
        continue;
      }
      String location = input[i].substring(pp.getIndex());
      System.out.println(" on " + d + " in " + location);
    }
  }
}