如何在android中将字符串(Date)转换为gregorian日历

时间:2014-09-16 07:24:35

标签: android datetime simpledateformat gregorian-calendar

我有一个像14-9-2014这样的字符串,我想把它转换为格里高利历,我已经搜索并尝试了很多方法,但我无法得到任何解决方案,那么任何人都可以告诉我如何转换它?谢谢

3 个答案:

答案 0 :(得分:3)

使用SimpleDateFormat解析日期,然后将其分配给日历。

DateFormat df = new SimpleDateFormat("dd MM yyyy");
Date date = df.parse("14-9-2014");
Calendar cal = Calendar.getInstance();
cal.setTime(date);

第三行可以替换为:

Calendar cal = new GregorianCalendar();

答案 1 :(得分:1)

看看这个link

SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");    
Calendar calendar = new GregorianCalendar(2014,9,14,12,51,56);

int year       = calendar.get(Calendar.YEAR);
int month      = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); 
int dayOfWeek  = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);

int hour       = calendar.get(Calendar.HOUR);        // 12 hour clock
int hourOfDay  = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute     = calendar.get(Calendar.MINUTE);
int second     = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);

System.out.println(sdf.format(calendar.getTime()));

System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);

System.out.println("hour \t\t: " + hour);
System.out.println("hourOfDay \t: " + hourOfDay);
System.out.println("minute \t\t: " + minute);
System.out.println("second \t\t: " + second);
System.out.println("millisecond \t: " + millisecond);

答案 2 :(得分:0)

试试这个:

SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy", context.getResources().getConfiguration().locale);

Date date = formatter.parse("14-9-2014");
Calendar c = new GregorianCalendar();
c.setTime(date);