从公历转换为儒略历 [英] Convert from Gregorian to Julian calendar

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

问题描述

我需要创建一个程序,该程序从 .csv 文件读取日期并将其转换为13天。我已经这样做了,但是不知何故它没有添加以下日期。它也会持续30天,例如 2001-12-42 不会发生。

I need to create a program that reads dates from a .csv file and convert it so that 13 days are added. I already did that but somehow it does not add the following dates as wished. It also goes over 30 days, which is not supposed to happen for example 2001-12-42.

public static void main(String[] args) throws FileNotFoundException, ParseException {
    File fread = new File("src/daten-greg.csv");
    File fwrite = new File("src/daten-jul.csv");

    Scanner s = new Scanner(fread);
    PrintStream print = new PrintStream(fwrite);

    while(s.hasNext()) {
        String[] line = s.nextLine().split(" ");
        print.println(String.join(" ", Convert(line)));
    }

    s.close();
    print.close();
}

private static String[] Convert(String[] value) throws ParseException {
    for (int i = 0; i < value.length; i+=1)
        value[i] = ToJulianisch(value[i]);

    return value;
}

private static String ToJulianisch(String date) throws ParseException {
    SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-mm-dd");
    Date d = sdf.parse(date);


    Calendar c = Calendar.getInstance();
    c.setTime(d);

    int actDay = c.get(Calendar.DAY_OF_MONTH);
    int actMonth = c.get(Calendar.MONTH) + 1 ;
    int actYear = c.get(Calendar.YEAR);
    actDay -= 13;

    if(actDay - 13 < 1) {
        actMonth -= 1;
        if(actMonth < 1) {
            actMonth = 12;
            actYear -= 1;
        }   
        Calendar k = Calendar.getInstance();
        k.set(Calendar.YEAR, actYear);
        k.set(Calendar.MONTH, actMonth - 1);
        actDay = k.getActualMaximum(Calendar.DAY_OF_MONTH) + actDay;
    }

    return String.format("%s-%s-%s", actYear, actMonth, actDay);
}


推荐答案

您要从 actDay 两次,首先在 actDay- = 13 中,然后在 if(actDay-13< 1)。在 if 块内,然后将小于14的值添加到每月的天数中,导致每月的某天溢出。

You are subtracting 13 from actDay twice, first in actDay-=13 and again for if(actDay - 13 < 1). Inside the if block, you then add the value which is less than 14 to the number of days per month, resulting in overflowing the day of month.

如果您只想从给定日期减去13天,则应使用 c.set(Calendar.DAY_OF_MONTH,actDay-13) 。这样可以在 Calendar 对象内部正确处理减法,然后可以使用

If you simply want to subtract 13 days from the given date, you should use c.set(Calendar.DAY_OF_MONTH,actDay-13). This will handle the subtraction correctly inside the Calendar object and you can then use

actDay = c.get(Calendar.DAY_OF_MONTH);
int actMonth = c.get(Calendar.MONTH) + 1 ;
int actYear = c.get(Calendar.YEAR);
return String.format("%s-%s-%s", actYear, actMonth, actDay);

这篇关于从公历转换为儒略历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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