java 格式化日期并返回日期,而不是字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35913647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:45:04  来源:igfitidea点击:

Format a Date and returning a Date, not a String

javaandroiddate

提问by Don

I need to get the Date of the current time with the following format "yyyy-MM-dd'T'HH:mm:ss"

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

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

I know how to format a Date using SimpleDateFormat. At the end I get a String. But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?

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

If I just return the Date, it is a Date but it is not properly formatted:

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

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

EDIT: Unfortunately I need to get the outcome as a Date, not a String, so I cannot use sdf.format(New Date().getTime()) as this returns a String. Also, the Date I need to return is the Date of the current time, not from a static String. I hope that clarifies

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

回答by Kevin Cruijssen

But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?

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

Since you know the DateTime-Format, it's actually pretty easy to format from Date to String and vice-versa. I would personally make a separate class with a string-to-date and date-to-string conversion method:

由于您知道 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;
        }
    }
}

Usage:

用法:

// 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);

回答by Basil Bourque

tl;dr

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

时间

The modern approach uses the java.timeclasses.

现代方法使用java.time类。

Capture the current moment in UTC.

以 UTC 格式捕获当前时刻。

Instant instant = Instant.now() ;

View that same moment through the wall-clock time used by the people of a particular region (a time zone).

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

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

You want to generate a string representing this value in a format that lacks any indication of time zone or offset-from-UTC. I do not recommend this. Unless the context where read by the user is absolutely clear about the implicit zone/offset, you are introducing ambiguity in your results. But if you insist, the java.timeclasses predefine a formatter object for that formatting pattern: DateTimeFormatter.ISO_LOCAL_DATE_TIME.

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

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


About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

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

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

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

Where to obtain the java.time classes?

从哪里获得 java.time 类?

回答by rocket

To format a data field do this

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

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();
        }

The above works for me perfectly.

以上对我来说完美无缺。

回答by Gaurav Rawal

use my code, I hope it's works for you......

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

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

回答by jonhid

Try this way

试试这个方法

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

Date date = sdf.parse("2016-03-10....");

回答by RSatpute

If you want Stringto Dateconversion, you need to parse Datein Stringformat using DateFormat. This is an example -

如果你想StringDate转换,你需要分析DateString使用的格式DateFormat。这是一个例子——

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

回答by Rohit Heera

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);

    }

回答by Madvesha k

Time Format should be same or else get time parser exception come

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

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);

回答by Sahil Sehgal

Yes u can :) you can convert back a String to a Date.

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

This method will help you: Date parse(String date);

此方法将帮助您: Date parse(String date);

It returns Date class object. You just have to pass the date in String format in this method.

它返回 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);
   }
}

回答by Martin Hansen

a parse method should be available to you. Use intellisense to check what methods your objects have :) Or simply look at the javadoc, most IDE's have an option to open the java files.

您应该可以使用解析方法。使用智能感知检查您的对象有哪些方法:) 或者简单地查看 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);