2012-08-01 181 views
1

我从数据库获取日期值,作为long值。我将此转换为字符串使用解析函数。下面给出的是我的代码将长字符串转换为日期

Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(strDate1); 

,但应用程序崩溃时,这个代码是executing.it将成功执行,如果

strDate1="12/30/2012". 

,但我有这个值作为“”(pzudo值)。

我该怎么做?

编辑:

我很日期值保存到DB为INTEGER。从DB我得到这个值,并转换为string.this是实际strDate1值

strDate1="1346524199000" 
+3

*你的'长'值代表什么?它存储什么,谁在存储它?如果它意味着(比如说)从Unix时代开始“毫秒”或者一些可怕的伪文本数字表示,那么它会产生一个*大*差。 – 2012-08-01 06:02:23

+0

你可以剥掉最后3个字符,然后使用你的价值? – Aviral 2012-08-01 06:18:26

回答

0

试试这个

Date date1 = new SimpleDateFormat("MMddyyyySSS").parse(strDate1); 

希望它会为12302012235的作品,但我认为235毫秒。

0

你可以试试下面的代码:

private Date getGMTDate(long date) { 
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
      "yyyy-MMM-dd HH:mm:ss"); 
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); 
    SimpleDateFormat dateFormatLocal = new SimpleDateFormat(
      "yyyy-MMM-dd HH:mm:ss"); 

    Date temp = new Date(date); 

    try { 
     return dateFormatLocal.parse(dateFormatGmt.format(temp)); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return temp; 
} 

我希望这会帮助你。

2

试试这个,

SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); 
    Date dateD=new Date(); 
    dateD.setTime(LongTime); 
    date=dateFormat.format(dateD); 
0

我得到了answer.actually我想的字符串转换日期仅比较values.since只要我得到的价值我直接使用功能的compareTo做this.avoided长转换为字符串和字符串日期conversion.thank大家支持。

+0

这个很长的值实际上是以毫秒为单位的时间我猜! – Android 2012-08-01 08:37:26

4

试试下面的代码段:

 Calendar c = Calendar.getInstance(); 
     c.setTimeInMillis(Long.parseLong(val));   
     Date d = (Date) c.getTime();   
     SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");  
     String time = format.format(d);//this variable time contains the time in the format of "day/month/year".  
1

的Java 8,转换长毫秒日期由给定的日期格式模式字符串。如果你有一个很长的毫秒,并想在指定的时区和模式中将它们转换为日期字符串,那么你可以使用它: -

dateInMs是DateTime的一个长整型值。

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") 
        .format(Instant.ofEpochMilli(dateInMs).atZone(ZoneId.of("Europe/London")))