我得到这样的系统时间(Thu Nov 14 14:38:16 IST 2013
),我必须将其转换为(MM/dd/yy
)。我尝试并在解析时遇到错误是我的代码,
String stime = calendar.getTime().toString();
System.out.println(" time is " +stime);
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date dateCC = formatter.parse(stime);
calendar.setTime(dateCC);
错误是NullpointerException,但我想要这种格式的日期(MM/dd/yy
)。请告诉我我做了什么错误?
答案 0 :(得分:1)
Date
本身没有格式。它仅表示自纪元(1970年1月1日格林威治标准时间00:00:00)以来的时间。因此,说您希望以特定格式获取Date
没有意义。但是,您可以使用SimpleDateFormat
来获取格式化的字符串表示形式。
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
String dateString = formatter.format(calendar.getTime());
答案 1 :(得分:1)
您必须使用所需的格式创建SimpleDateFormat实例,然后使用它来格式化Date或Time对象,如下所示:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
System.out.println(sdf.format(Calendar.getInstance().getTime()));
在需要帮助的格式时,请参阅此JavaDoc。
答案 2 :(得分:0)
试试这个:
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String stime = formatter.format(calendar.getTime());
System.out.println(stime);
Date dateCC = formatter.parse(stime);
calendar.setTime(dateCC);
System.out.println(calendar.getTime());
答案 3 :(得分:0)
Java 7中的Joda-Time 2.3。
org.joda.time.DateTimeZone losAngelesTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");
org.joda.time.DateTime nowInCalifornia = new org.joda.time.DateTime( losAngelesTimeZone );
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("MM/dd/yy");
String nowInCaliforniaAsString = formatter.print( nowInCalifornia );
System.out.println( "nowInCaliforniaAsString: " + nowInCaliforniaAsString );