如何正确格式化日期?

编程入门 行业动态 更新时间:2024-10-10 10:32:46
本文介绍了如何正确格式化日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

下面显示的函数返回日期,例如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.

更多推荐

如何正确格式化日期?

本文发布于:2023-05-28 00:49:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/308279.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何正确   日期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!