Java 如何将日期转换为字符串并再次转换为日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19492419/
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-08-12 17:44:03  来源:igfitidea点击:

How to convert date to string and to date again?

javastringdatesimpledateformat

提问by ayampenyet

Hi i want to convert the current date to this format YYYY-MM-DD. However, it will convert the date into Stringformat, but i want to convert it back into Dateformat. So can anyone advise on this?

嗨,我想将当前日期转换为这种格式YYYY-MM-DD。但是,它会将日期转换为String格式,但我想将其转换回Date格式。那么有人可以就此提出建议吗?

This is my code so far

到目前为止,这是我的代码

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 Date date = new Date();
 String datestring = dateFormat.format(date); 

采纳答案by Kanchan

try this:

尝试这个:

 String DATE_FORMAT_NOW = "yyyy-MM-dd";
 Date date = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
 String stringDate = sdf.format(date );
    try {
        Date date2 = sdf.parse(stringDate);
    } catch(ParseException e){
     //Exception handling
    } catch(Exception e){
     //handle exception
    }

回答by qqilihq

Use DateFormat#parse(String):

使用DateFormat#parse(String)

Date date = dateFormat.parse("2013-10-22");

回答by Yasa

try this function

试试这个功能

public static Date StringToDate(String strDate) throws ModuleException {
    Date dtReturn = null;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
    try {
        dtReturn = simpleDateFormat.parse(strDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dtReturn;
}

回答by David Pham

Convert Date to String using this function

使用此函数将日期转换为字符串

public String convertDateToString(Date date, String format) {
        String dateStr = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            dateStr = df.format(date);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return dateStr;
    }

From Convert Date to String in Java. And convert string to date again

在 Java 中转换日期到字符串。并再次将字符串转换为日期

public Date convertStringToDate(String dateStr, String format) {
        Date date = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            date = df.parse(dateStr);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return date;
    }

From Convert String to date in Java

Java 中将字符串转换为日期

回答by Shiva

For converting date to string check this thread

要将日期转换为字符串,请检查此线程

Convert java.util.Date to String

将 java.util.Date 转换为字符串

And for converting string to date try this,

并将字符串转换为日期试试这个,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StringToDate
{
    public static void main(String[] args) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        String strDate = "14/03/2003 08:05:10";     
        System.out.println("Date - " + sdf.parse(strDate));
    }
}

回答by Basil Bourque

tl;dr

tl;博士

How to convert date to string and to date again?

如何将日期转换为字符串并再次转换为日期?

LocalDate.now().toString()

2017-01-23

2017-01-23

…and…

…和…

LocalDate.parse( "2017-01-23" )

java.time

时间

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

问题使用与最早版本的 Java 捆绑在一起的麻烦的旧日期时间类。这些类现在是遗留的,被 Java 8、Java 9 和更高版本中内置的 java.time 类所取代。

Determining today's date requires a time zone. For any given moment the date varies around the globe by zone.

确定今天的日期需要时区。对于任何给定时刻,日期因地区而异。

If not supplied by you, your JVM's current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

如果您未提供,则应用 JVM 的当前默认时区。该默认值可以在运行时随时更改,因此不可靠。我建议您始终指定所需/预期的时区。

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

您想要的 YYYY-MM-DD 格式恰好符​​合 ISO 8601 标准。

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parseand LocalDate::toStringwithout specifying a formatting pattern.

在解析/生成字符串时,java.time 类默认使用该标准。所以你可以简单地调用LocalDate::parse并且LocalDate::toString不指定格式模式。

String s = ld.toString() ;

To parse:

解析:

LocalDate ld = LocalDate.parse( s ) ;


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

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多