如何正确格式化日期? [英] How to properly format the date?

查看:56
本文介绍了如何正确格式化日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面显示的函数返回日期,例如2010 年 9 月 8 日星期六 00:00 PDT".但我希望以yyyy-MM-dd HH:mm"格式获取日期.这段代码有什么问题?

The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT 2010". But I expected to get the date in the following format "yyyy-MM-dd HH:mm". What's wrong in this code?

String date = "2010-08-25";
String time = "00:00";

也在一台笔记本电脑中输出,例如23:45 是 11:45.如何准确定义 24 格式?

Also in one laptop the output for,e.g. 23:45 is 11:45. How can I define exactly the 24 format?

private static Date date(final String date,final String time) {
       final Calendar calendar = Calendar.getInstance();
       String[] ymd = date.split("-");
       int year = Integer.parseInt(ymd[0]);
       int month = Integer.parseInt(ymd[1]);
       int day = Integer.parseInt(ymd[2]);
       String[] hm = time.split(":");
       int hour = Integer.parseInt(hm[0]);
       int minute = Integer.parseInt(hm[1]);
       calendar.set(Calendar.YEAR,year);
       calendar.set(Calendar.MONTH,month);
       calendar.set(Calendar.DAY_OF_MONTH,day);
       calendar.set(Calendar.HOUR,hour);
       calendar.set(Calendar.MINUTE,minute);
       SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm");
       Date d = calendar.getTime();
       String dateString= dateFormat.format(d);
       Date result = null;
       try {
            result = (Date)dateFormat.parse(dateString);
       } catch (ParseException e) {
            e.printStackTrace();
       }
       return result;
    }

推荐答案

你是如何打印返回结果的?如果你只是使用 System.out.println(date("2010-08-25", "00:00") 那么你可能会得到 Sat Sep 8 00:00 PDT 2010code> 取决于您在跑步机中当前的日期时间格式设置.但是您可以做的是:

How did you print out the return result? If you simply use System.out.println(date("2010-08-25", "00:00") then you might get Sat Sep 8 00:00 PDT 2010 depending on your current date time format setting in your running machine. But well what you can do is:

Date d = date("2010-08-25", "00:00");
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d));

只是好奇你为什么要为这整个过程烦恼,因为你可以通过连接初始日期和时间字符串来简单地得到结果.

Just curious why do you bother with this whole process as you can simple get the result by concatenate your initial date and time string.

这篇关于如何正确格式化日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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