将 Date 对象转换为日历对象

Converting a Date object to a calendar object(将 Date 对象转换为日历对象)
本文介绍了将 Date 对象转换为日历对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

所以我从表单中的传入对象中获取日期属性:

So I get a date attribute from an incoming object in the form:

Tue May 24 05:05:16 EDT 2011

我正在编写一个简单的辅助方法来将其转换为日历方法,我使用的是以下代码:

I am writing a simple helper method to convert it to a calendar method, I was using the following code:

    public static Calendar DateToCalendar(Date date ) 
{ 
 Calendar cal = null;
 try {   
  DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
  date = (Date)formatter.parse(date.toString()); 
  cal=Calendar.getInstance();
  cal.setTime(date);
  }
  catch (ParseException e)
  {
      System.out.println("Exception :"+e);  
  }  
  return cal;
 }

为了模拟传入的对象,我只是在当前使用的代码中分配值:

To simulate the incoming object I am just assigning the values within the code currently using:

private Date m_lastActivityDate = new Date();

但是,一旦方法到达,这会给我一个空指针:

However this is givin me a null pointer once the method reaches:

date = (Date)formatter.parse(date.toString()); 

推荐答案

这是你的方法:

public static Calendar toCalendar(Date date){ 
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal;
}

你所做的一切都是错误和不必要的.

Everything else you are doing is both wrong and unnecessary.

顺便说一句,Java 命名约定建议方法名称以小写字母开头,因此应该是:dateToCalendartoCalendar(如图所示).

BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).

好的,让我们挤一下你的代码,好吗?

OK, let's milk your code, shall we?

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString()); 

DateFormat 用于将字符串转换为日期(parse())或将日期转换为字符串(format()).您正在使用它将日期的字符串表示解析回日期.这不可能吧?

DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?

这篇关于将 Date 对象转换为日历对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)