Java如何获取Date类型且格式为yyyy-mm-dd的日期数据?

我现在用:
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
Date date=new Date();
sdf.format(date);
可以获得格式如“yyyy-mm-dd”的日期数据,但类型为String.
如何保持格式不变,但类型为Date?

@return返回长时间格式 yyyy-MM-dd HH:mm:ss
*/  public static Date getSqlDate() {
Date sqlDate = new java.sql.Date(new Date().getTime());
return sqlDate;  }  
/**
* 获取现在时间

*
* @return返回长时间格式 yyyy-MM-dd HH:mm:ss
*/  public static Date getNowDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;  }

温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-06-21

@return返回长时间格式 yyyy-MM-dd HH:mm:ss

*/  public static Date getSqlDate() {

Date sqlDate = new java.sql.Date(new Date().getTime());

return sqlDate;  }  

/**

* 获取现在时间

@return返回长时间格式 yyyy-MM-dd HH:mm:ss

*/  public static Date getNowDate() {

Date currentTime = new Date();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dateString = formatter.format(currentTime);

ParsePosition pos = new ParsePosition(8);

java.sql 类 Date

java.lang.Object

java.util.Date

java.sql.Date

所有已实现的接口:

Serializable,Cloneable,Comparable<Date>

public class Dateextends Date

概述:一个包装了毫秒值的瘦包装器 (thin wrapper),它允许 JDBC 将毫秒值标识为 SQL DATE 值。毫秒值表示自 1970 年 1 月 1 日 00:00:00 GMT 以来经过的毫秒数。

为了与 SQL DATE 的定义一致,由 java.sql.Date 实例包装的毫秒值必须通过将小时、分钟、秒和毫秒设置为与该实例相关的特定时区中的零来“规范化”。

以上内容参考:百度百科-date

本回答被网友采纳
第2个回答  推荐于2019-08-13

第一种方法:

/**
*将字符串格式yyyyMMdd的字符串转为日期,格式"yyyy-MM-dd"
*
* @param date 日期字符串
* @return 返回格式化的日期
* @throws ParseException 分析时意外地出现了错误异常
*/
public static String strToDateFormat(String date) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
formatter.setLenient(false);
Date newDate= formatter.parse(date);
formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(newDate);
}

第二种方法:


DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String nowdayTime = dateFormat.format(newDate());
Date nowDate = dateFormat.parse(nowdayTime);
简单思路就是:先通过DateFormat将当前Date转化为String格式日期,再通过DateFormat解析该String日期,再次生成Date。

本回答被网友采纳
第3个回答  2010-11-28
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
Date date=new Date();
String dateStr = sdf.format(date);
Date mydate = sdf.parse(dateStr);
/**试试看 */本回答被网友采纳
第4个回答  推荐于2018-01-19
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Date date = sdf.parse(sdf.format(new Date()));本回答被网友采纳
相似回答