【问题标题】:Date conversion in value read from excel in java从java中的excel读取的值中的日期转换
【发布时间】:2017-09-19 11:47:40
【问题描述】:

队友,

我有一个 Date 对象,它在从 excel 读取后填充了一个值

Date mydate = cell.getDateCellValue(); 

加载的值为 *"Sat Jan 09 00:00:00 IST 2016"

我不知道为什么这个格式值是从 excel 中给出的,虽然它在 excel 中以不同的格式显示。

我想将此 DATE 转换为 dd-mm-yyyy 格式。如何做到这一点?

试过了

String ms= "Sat Jan 09 00:00:00 IST 2016"   ;  
          SimpleDateFormat formater = new SimpleDateFormat("mm-dd-yy");      
          Date result = formater.parse(ms);
          System.out.println(result); 

但输出与输入相同。

【问题讨论】:

  • Tue Sep 19 13:52:47 CEST 2017System.out.println(new Date()); 的输出,因此您只能格式化输出,但不能格式化日期的保存方式
  • 您正在尝试使用模式“mm-dd-yy”解析字符串“Sat Jan 09 00:00:00 IST 2016”。这怎么可能行得通?您为什么要尝试将字符串解析为日期,因为 getDateCellValue() 已经返回一个日期对象,您只需要按照您想要的方式进行格式化?解析 = 字符串到日期。格式 = 日期到字符串。
  • 还有mm-dd-yyminutes-day-year

标签: java jsp


【解决方案1】:

您需要创建自己的 Date 类并使用您希望它返回的任何格式覆盖 toString 方法#ApachePOI

public class CustomDate extends Date
{

public CustomDate(String string) 
{
    super(string);
}

@Override
public String toString()
{
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
    String format = formatter.format(this);

    return format;
}
}

以及主要方法

public static void main(String[] args) 
{
    Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
    String dateString  = date.toString();

    CustomDate customDate = new CustomDate(dateString);

    System.out.println(dateString);
    System.out.println(customDate.toString());
}

在 toString 方法中使用任何你想要的格式

【讨论】:

    【解决方案2】:

    不要将日期时间对象与表示其值的文本混为一谈。 java.util.Date 没有“格式”。您看到的是由该对象的 toString 方法生成的文本。该文本在对象内部不存在。那个类的toString 撒谎,将 JVM 当前的默认时区应用于实际存储在其中的 UTC 值。完全避免使用此类的众多原因之一。

    Date 类是麻烦的旧日期时间类的一部分,这些类现在是遗留的,被 java.time 类所取代。

    将您的 java.util.Date 对象转换为 Instant

    在 Java 8 及更高版本中,寻找添加到旧类的新转换方法。对于 Java 6 和 Java 7,您将使用 ThreeTen-Backport 项目。在那里你会找到一个提供转换方法的DateTimeUtil 类。

    从我们的Instant,我们可以得到一个约会。但首先我们必须应用一个时区来将 Instant 从 UTC 移动到您想要感知日期的区域。对于任何给定的时刻,日期在全球范围内因区域而异。

    ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
    ZonedDateTime zdt = instant.atZone( z ) ;
    

    使用DateTimeFormatter 生成字符串。

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd -MM-uuuu" , Locale.US ) ;
    String output = zdt.format( f ) ;
    

    【讨论】:

    • 感谢罗勒的投入
    猜你喜欢
    • 2017-09-02
    • 2019-07-31
    • 2018-04-14
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    相关资源
    最近更新 更多