更改Date Java的格式 [英] Change the format of Date Java

查看:414
本文介绍了更改Date Java的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Date对象的格式为

I've the Date object with the format

 /107/2013 12:00:00 AM

我的预期价值:

2013-07-01

我是怎么做到的?

我正在尝试使用此代码

public static  Date  formatearFecha( Date fecha ){

    String fechaString = new SimpleDateFormat("yyyy-MM-dd").format(fecha) ;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date fechaFormateada = null;
    try {
        fechaFormateada = df.parse(fechaString);
    } catch (ParseException ex) {
        Logger.getLogger(TestThings.class.getName()).log(Level.SEVERE, null, ex);
    }
    return fechaFormateada;

}

当我尝试进行测试时,我得到了这个:

When I try to make a test I get this:

 System.out.println( formatearFecha(myDate) );
 Mon Sep 30 00:00:00 COT 2013

更新:

我的问题是在sql中将java.util.Date更改为java.sql.Date

我解决了这个问题:

my problem was in sql change to java.util.Date to java.sql.Date
I solve this so:

private  String formatearFecha( Date fecha ){
    return new SimpleDateFormat("yyyy-MM-dd").format(fecha);
}

private java.sql.Date stringToSQLDate( String fecString ){

    java.sql.Date fecFormatoDate = null;
    try {
          SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd", new Locale("es", "ES"));
         return  new java.sql.Date(sdf.parse(fecString).getTime());
    } catch (ParseException ex) { }
    return null;
}

并测试:

stringToSQLDate( formatearFecha( myDate ) );


推荐答案

首先:java.util.Date对象 never 有一个格式存储在其中。您可以将Date视为包含自UTC时区的纪元以来的长毫秒值的对象。该类有几个方法,但没有时区偏移,格式化模式等存储在其中。

First of all: java.util.Date object never has a format stored in it. You can think of Date as an object containing long value of milliseconds since epoch at UTC timezone. The class has few methods, but no timezone offset, formatted pattern etc stored in it.

其次,以下基本代码可用于格式化日期为yyyy-MM- dd在你机器的语言环境中:

Secondly, following basic code can be used to format a date to yyyy-MM-dd in your machine's locale:

Date mydate = ...
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String mydateStr = df.format(mydate);

同样,您可以将字符串/ 107/2013 12:00:00 AM解析为机器的语言环境中的日期对象如下:

Similarly, you can parse a string "/107/2013 12:00:00 AM" into a date object in your machine's locale like this:

String mydateStr = "/107/2013 12:00:00 AM";
DateFormat df = new SimpleDateFormat("/dMM/yyyy HH:mm:ss aa");
Date mydate = df.parse(mydateStr);

上面的两个方法可用于将格式化的日期字符串从一个更改为另一个。

Two method above can be used to change a formatted date string from one into the other.

请参阅有关格式代码的详细信息,请参阅SimpleDateFormat的javadoc

这篇关于更改Date Java的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆