繁体   English   中英

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

[英]Format a Date and returning a Date, not a String

我需要使用以下格式“ 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()); 

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

试试这个

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

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

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

由于您知道DateTime格式,因此实际上很容易将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);

tl; dr

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及更高版本中。 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

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

要了解更多信息,请参见Oracle教程 并在Stack Overflow中搜索许多示例和说明。 规格为JSR 310

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

在哪里获取java.time类?

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

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

以上对我来说很完美。

解析方法应该对您可用。 使用intellisense检查您的对象具有哪些方法:)或仅查看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);

尝试这个:

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

如果要将String转换为Date ,则需要使用DateFormatString格式解析Date 这是一个例子-

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

    }

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

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

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

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

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

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

它返回Date类对象。 您只需要在此方法中以String格式传递日期。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM