如何获得的时间和日期的日期时间戳 [英] How to get time and Date from datetime stamp

查看:179
本文介绍了如何获得的时间和日期的日期时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1串状 2011年8月29日上午11时16分12秒,我想保存在诸如日期= 2011年8月29日和时间变量=上午11时16分12秒

i have 1 string like 8/29/2011 11:16:12 AM i want to save in variable like date = 8/29/2011 and time = 11:16:12 AM

怎么会是可能的? 你可以给我的例子?

how would is possible? can you give me example?

推荐答案

做的方法之一是它解析为一个Date对象,并再次重新格式化:

One way to do is parse it to a date object and reformat it again:

    try {
        DateFormat f = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
        Date d = f.parse("8/29/2011 11:16:12 AM");
        DateFormat date = new SimpleDateFormat("MM/dd/yyyy");
        DateFormat time = new SimpleDateFormat("hh:mm:ss a");
        System.out.println("Date: " + date.format(d));
        System.out.println("Time: " + time.format(d));
    } catch (ParseException e) {
        e.printStackTrace();
    }

如果你只是想它切成日期时间段,只需用分割得到片

If you just want to slice it into date-time pieces, just use split to get pieces

    String date = "8/29/2011 11:16:12 AM";
    String[] parts = date.split(" ");
    System.out.println("Date: " + parts[0]);
    System.out.println("Time: " + parts[1] + " " + parts[2]);

    String date = "8/29/2011 11:16:12 AM";
    System.out.println("Date: " + date.substring(0, date.indexOf(' ')));
    System.out.println("Time: " + date.substring(date.indexOf(' ') + 1));

但是,这种方法是脆弱的。

But this approach is fragile.

这篇关于如何获得的时间和日期的日期时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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