【问题标题】:Format a Date and returning a Date, not a String格式化日期并返回日期,而不是字符串
【发布时间】:2016-06-25 03:06:48
【问题描述】:

我需要获取当前时间的日期,格式如下“yyyy-MM-dd'T'HH:mm:ss”

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");   

我知道如何使用 SimpleDateFormat 格式化日期。最后我得到一个字符串。但我需要获取格式化的日期,而不是字符串,据我所知,我无法将字符串转换回日期,可以吗?

如果我只返回日期,它是一个日期,但格式不正确:

Timestamp ts = new Timestamp(new Date().getTime()); 

编辑: 不幸的是,我需要将结果作为日期,而不是字符串,所以我不能使用 sdf.format(New Date().getTime()),因为这会返回一个字符串。 另外,我需要返回的日期是当前时间的日期,而不是来自静态字符串。我希望澄清

【问题讨论】:

  • 这个问题没有真正的意义:Date 只是一个瞬间,它没有格式。
  • new Date() 已经是 Date,而不是 String
  • 您通过new Date() 获取当前日期。正如我之前已经评论过的,Date 对象不携带格式。只有当您将Date 转换为String 时,格式才会发挥作用。
  • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。许多 java.time 功能在ThreeTen-Backport 项目中被反向移植到Java 6 和Java 7。在ThreeTenABP 项目中进一步适用于早期的Android。见How to use ThreeTenABP…

标签: java android date


【解决方案1】:

但我需要获取格式化的日期,而不是字符串,据我所知,我无法将字符串转换回日期,可以吗?

既然您知道 DateTime-Format,实际上将 Date 格式化为 String 非常容易,反之亦然。我个人会用字符串到日期和日期到字符串的转换方法创建一个单独的类:

public class DateConverter{

    public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    public static Date convertStringToDate(final String str){
        try{
            return DATE_FORMAT.parse(str);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }

    public static String convertDateToString(final Date date){
        try{
            return DATE_FORMAT.format(date);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }
}

用法:

// Current date-time:
Date date = new Date();

// Convert the date to a String and print it
String formattedDate = DateConverter.convertDateToString(date);
System.out.println(formattedDate);

// Somewhere else in the code we have a String date and want to convert it back into a Date-object:
Date convertedDate = DateConverter.convertStringToDate(formattedDate);

【讨论】:

  • 嗨,Kevin,这看起来很有希望,不幸的是,我无法使用 DateTimeFormat 访问方法 getFormat。我已经导入:import org.joda.time.format.DateTimeFormat;
  • @Don 啊,很抱歉,我在当前正在处理的项目中使用相同的代码,但是对于大多数默认 Java 方法/类,我必须使用 GWT。 (PS /无关:我使用的导入是import com.google.gwt.i18n.client.DateTimeFormat;)我已经编辑了我的答案,所以它现在使用SimpleDateFormat。其余代码和用法应该还是一样的。
  • 凯文您好,感谢您的编辑,我现在可以使用您的课程。不幸的是,有什么问题,这是我记录的内容: formattedDate == 2016-03-11T09:20:10.650 convertDate == Fri Mar 11 09:20:10 CET 2016 所以最终输出没有按照所需格式格式化.也许是因为它被格式化了两次,所以它回到了最初的默认格式?
  • @Don 我认为您误解了日期的工作原理。当您尝试打印日期时:System.out.println(new Date()); 它将以 PC 设置中的默认格式打印日期。如果您想以自己的格式打印,请使用SimpleDateFormat。日期对象(如我的回答中的 Date convertedDate)没有任何格式。只有在打印时,您才能给它一个格式(使用SimpleDateFormat)或以PC的默认格式打印(这就是您只需调用System.out.println("convertedDate == " + convertedDate);即可完成的操作
  • @delive 你有问题吗?.. :S
【解决方案2】:

tl;博士

ZonedDateTime.now()                                   // Capture the current moment as seen by the people of a region representing by the JVM’s current default time zone. 
    .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String representing that value using a standard format that omits any indication of zone/offset (potentially ambiguous).

java.time

现代方法使用 java.time 类。

以 UTC 捕捉当前时刻。

Instant instant = Instant.now() ;

通过特定地区(时区)的人们使用的挂钟时间查看同一时刻。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, same point on the timeline, different wall-clock time.

您希望生成一个表示该值的字符串,其格式不包含任何时区指示或与 UTC 的偏移量。我不推荐这个。除非用户阅读的上下文绝对清楚隐式区域/偏移量,否则您将在结果中引入歧义。但是,如果您坚持,java.time 类会为该格式化模式预定义一个格式化程序对象:DateTimeFormatter.ISO_LOCAL_DATE_TIME

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;

关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

从哪里获得 java.time 类?

【讨论】:

    【解决方案3】:

    试试这个方法

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
    
    Date date = sdf.parse("2016-03-10....");
    

    【讨论】:

      【解决方案4】:

      使用我的代码,我希望它对你有用......

       SimpleDateFormat dateFormat= new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
       String str_date=dateFormat.format(new Date());
      

      【讨论】:

        【解决方案5】:

        要格式化数据字段,请执行此操作

        Date today = new Date();
                //formatting date in Java using SimpleDateFormat
                SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String date2= DATE_FORMAT.format(today);
        
                Date date;
                try {
                    date = DATE_FORMAT.parse(date2);
                     setDate(date); //make use of the date
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        

        以上方法对我来说很完美。

        【讨论】:

        • 它是否给您请求的Date 和请求的格式,而不是String?无论如何,请不要教年轻人使用早已过时且臭名昭著的麻烦SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 中做得更好。是的,您可以在 Android 上使用它。对于较旧的 Android,请参阅 How to use ThreeTenABP in Android Project
        【解决方案6】:

        您应该可以使用 parse 方法。使用智能感知检查您的对象有哪些方法:) 或者只是查看 javadoc,大多数 IDE 都有打开 java 文件的选项。

        String dateString = "2016-01-01T00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date d = sdf.parse(dateString);
        

        【讨论】:

        • 感谢您的回答马丁。在您的解决方案中,我应该使用 Long date1 = (new Date().getTime());字符串 dateString = date1.toString();作为格式化前的初始字符串?
        • 如果您只想要当前时间的date 对象,为什么不直接使用Date d = new Date() 那么您已经有了Date 对象?我不太确定你的问题到底是什么。我认为DatetoString() 方法没有按照您要求的模式格式化,所以这不起作用。
        • 也许我遗漏了一些东西,包括你在内的所有答案都从静态字符串日期开始,而我需要当前时间。如何使用 sdf.parse(dateString); dateString 是当前时间的字符串?对不起,如果我在某个地方弄错了
        • 如果只需要当前时间,使用Date d = new Date()即可。
        • 这将返回类似于“Thu Mar 10 11:50:26 CET 2016”的内容,这不是我需要的格式
        【解决方案7】:

        试试这个:

        LocalDateTime ldt = Instant.now()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDateTime()
        

        【讨论】:

        • 正确的代码,但不是一个好主意。 LocalDateTime 故意缺少任何时区或与 UTC 偏移的概念。所以它在这里的使用是丢弃有价值的信息(区域/偏移量)。
        【解决方案8】:

        如果你想要StringDate的转换,你需要使用DateFormatDate解析成String格式。这是一个例子-

            String target = "2016-03-10T15:54:49";
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            Date result =  df.parse(target);
        

        【讨论】:

          【解决方案9】:
          public String getCurrentDateTime() {
                  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                  // get current date time with Date()
                  Date date = new Date();
                  return dateFormat.format(date);
          
              }
          

          【讨论】:

            【解决方案10】:

            时间格式应该相同,否则会出现时间解析器异常

            String dateString = "03/26/2012 11:49:00 AM";
                SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
                Date convertedDate = new Date();
                try {
                    convertedDate = dateFormat.parse(dateString);
                } catch t(ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(convertedDate);
            

            【讨论】:

              【解决方案11】:

              是的,你可以:) 您可以将字符串转换回日期。

              这个方法对你有帮助:Date parse(String date);

              它返回 Date 类对象。您只需在此方法中以字符串格式传递日期即可。

              import java.text.*;
              import java.util.*;
              
              class Test {
                  public static void main(String[] args)  throws Throwable {
              
                  String date = "2016-03-10T04:05:00";
              
                  SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
              
                  Date d = s.parse(date);
              
                  System.out.println(d);
                 }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2023-04-07
                • 1970-01-01
                • 2018-09-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多