Java-毫秒到月/年(不仅是当前时间) [英] Java - Milliseconds to Month/Year (not just the current time)

查看:75
本文介绍了Java-毫秒到月/年(不仅是当前时间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个Java语言的算法,我想根据与每个对象相关的时间每月进行一次操作。

Say I have an algorithm in Java where I want to do something on a monthly basis based off the time associated with each object.

例如,如果对象a 的时间为 long t ,而 t 的时间为毫秒从那个时代开始,我怎么会发现 t 是2014年3月3日的时间?

So for example, if Object a has time long t, and t is in milliseconds since the epoch, how would I find out that t is a time in 03/2014?

问题,我如何在时间上向后迭代几个月-因此,如果我从2014年5月1日开始,如何准确地返回到4月,3月,2月等,而不必担心拥有28-31个问题一个月内有几天?我当时正在考虑使用 Calendar 类,但是不确定是否可以更新 MONTH 变量并使用它给我一个正确的毫秒值。例如,如果是3月31日,而我将月份更新为2月,然后突然认为是2月31日呢?

As a secondary question, how can I iterate over months backwards in time - so if I'm starting on May 1, 2014, how can I accurately go back to April, March, Feb, etc, without worrying about the whole problem of having 28 - 31 days in a month? I was considering using the Calendar class, but wasn't sure if I can just update the MONTH variable and have it give me a correct millisecond value. Like, what if it's March 31, and I update the month to February, and then suddenly it thinks it's Feb 31?

推荐答案

最简单的方法是使用 <$ c您在问题中提到的$ c> java.util.Calendar 类。您可以通过使用

The easiest way to do this is to use the java.util.Calendar class as you mention in your question. You can easily get an instance by using

//use whatever time zone your milliseconds originiate from
//there is another getter that takes a Locale, which may be useful depending on your context
Calander c = Calendar.getInstance(TimeZone.getDefault());

然后您可以使用

c.setTimeInMillis(t);

为了找出时间,可以使用 DateFormat 对象

In order to find out when this was, you can print out the result using a DateFormat object

DateFormat df = DateFormat.getInstance(DateFormat.SHORT);
System.out.println(df.format(c.getTime());

要在月份(或任何其他时间单位)中移动,您可以使用月字段将其添加到日历:

To move through the months (or any other unit of time), you would "add" to the calendar using the month field:

c.add(Calendar.MONTH, -2);

好消息是您可以使用 add()方法(用于任何其他时间单位)和 Calendar 类将根据需要适当调整日期,以您期望的方式(即日历 Locale 定义的文化上适当的方式)。

The good news is that you can use the add() method for any other time unit and the Calendar class will take care of properly adjusting the date as needed, in the way you expect (i.e., the culturally appropriate way defined by the Locale of the Calendar).

最后,您可以使用

long newTime = c.getTimeInMillis();

这篇关于Java-毫秒到月/年(不仅是当前时间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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