用户登录
用户注册

分享至

在Android中将字符串日期转换为时间戳?

  • 作者: 熙沫女神
  • 来源: 51数据库
  • 2022-10-25

问题描述

我想转换我的日期(字符串格式),例如2011 年 9 月 13 日,进入时间戳.我使用了下面的代码,但我得到了 2011-09-13 00:00:00.0因此.但我想要像 1312828200000 格式的时间戳.

I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0 as a result. But I want Timestamp like,1312828200000 format.

我不明白如何转换它.

我的代码:

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);

推荐答案

如果你使用 Date 对象的 getTime() 你会得到毫秒的时间.无需使用 Timestamp 即可获得结果.

If you use getTime() of Date object you will get time in millisecond. No need to use Timestamp to get your result.

String str_date="13-09-2011";
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

上面的代码会打印出你需要的类似 1312828200000 的东西,这是长值.

The above code will print something like 1312828200000 you need and this is long value.

软件
前端设计
程序设计
Java相关