转换日期为年和月 [英] Convert Date to Year and Month

查看:110
本文介绍了转换日期为年和月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的,我有显示日期的应用程序。现在我想那日起年和月转换为当前日期。

I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.

我的日期是像 - 29/03/2017

我想这个日期到年和月转换。

I want to convert this date into Year and Months.

对不起,我想你是不是能理解我的问题。我想在一年或几个月当前日期和上述日期的差异。

Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.

对不起,我的解释。

推荐答案

我发现我的答案使用日历类。

I found my answer using Calender class .

首先,我找到两个日子之间的差异,使用几天我找到了年和月。

First i find the difference between two days and using that days i found the years and months.

下面我发布我的code,我想帮助别人。

Here i post my code, which i think help to others.

int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;

getDateDiffString()方法。在这种方法中,我们需要传递结束日期

public static String getDateDiffString(String endDate)
    {
        try
        {
            Calendar cal = Calendar.getInstance();

            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
            Date dateTwo = dateFormat.parse(endDate); 

            long timeOne = cal.getTimeInMillis();
            long timeTwo = dateTwo.getTime();
            long oneDay = 1000 * 60 * 60 * 24;
            long delta = (timeTwo - timeOne) / oneDay;

            if (delta > 0) {
                return "" + delta + "";
            }
            else {
                delta *= -1;
                return "" + delta + "";
            }
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        return "";
    }

这篇关于转换日期为年和月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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