【问题标题】:Java gives me wrong time every time i try to get it [closed]每次我尝试获取它时,Java都会给我错误的时间[关闭]
【发布时间】:2014-11-20 11:42:54
【问题描述】:

我需要在 android 应用程序中获得正常的正确时间。但是每次我运行应用程序时,我都会得到错误的小时数和分钟数。这不是不正确的时区。每次运行应用程序,时间都不一样!我在这里搜索了问题,但没有找到适合我的答案。对此没有任何作用......为什么它在java中如此成问题?在 C# 中。例如,您只需写信即可获得时间:var time = DateTime.Now。我怎样才能得到正常的正确时间?我电脑上的时区设置为 UTC +02:00。 (乌克兰,基辅)。 我的代码:

Calendar curTime = new GregorianCalendar();
curTime.setTimeZone(TimeZone.getTimeZone("Ukraine/Kiev"));
DateFormat dateFormat = new SimpleDateFormat("HH:ss");
dateFormat.setCalendar(curTime);

String time = dateFormat.format(curTime.getTime());

【问题讨论】:

  • 你能分享一些代码吗?!
  • "每次运行应用,时间都不一样!"呃,你到底在期待什么?
  • 在android中获取时间的代码是什么,@Booger不要问C#代码!
  • 我已将代码添加到问题中。嗯,问题是,例如,现在我的时间是 19:05。如果我运行该应用程序,我会得到 16:54。然后,如果我第二次运行它,我可以得到 21:12 之类的东西
  • docs.oracle.com/javase/6/docs/api/java/text/…。您在dateFormat 中设置了小时和秒。试试HH:mm。

标签: java android datetime


【解决方案1】:

我希望这应该可行..乌克兰的时区是 GMT+3

  Date today = Calendar.getInstance().getTime();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
  sdf.setTimeZone(TimeZone.getTimeZone("GMT+3"));
  String date = sdf.format(today);

以上代码的输出::

  2014-09-25-09.51.23

【讨论】:

  • 这对我不起作用:(
【解决方案2】:

This 答案有一些时区可以在您的getTimeZone 方法中使用。

Calendar curTime = new GregorianCalendar();
curTime.setTimeZone(TimeZone.getTimeZone("Europe/Kiev"));
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
dateFormat.setCalendar(curTime);

String time = dateFormat.format(curTime.getTime());
System.out.println(time);

输出: 19:22

【讨论】:

  • 非常感谢!它有效
猜你喜欢
  • 2022-10-04
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 2019-03-12
  • 1970-01-01
相关资源
最近更新 更多