How do i convert a julian date 2456606 which stands for Nov 18 2013 to the string format 18/11/2013 using java APIs? I tried executing the below code but it is not giving me the right answer. Any corrections to the below code are welcome
String j = "2456606";
Date date = new SimpleDateFormat("yyyyD").parse(j);
String g = new SimpleDateFormat("dd.MM.yyyy").format(date);
System.out.println(g);
tl;dr
LocalDate.MIN.with (
java.time.temporal.JulianFields.MODIFIED_JULIAN_DAY ,
2_456_606L
)
2013-11-09
Other direction, from modern date to Julian Day.
LocalDate.of( 2013 , 11 , 9 )
.getLong ( java.time.temporal.JulianFields.JULIAN_DAY )
2456606
Details
Firstly, your comment:
the julian date to be 2456606 for nov 18 in the converter link mentioned below aa.usno.navy.mil/data/docs/JulianDate.php
…is incorrect. That web site returns November 9, 2013 for 2456606.
Your Navy web site defines Julian Date as a count of days since January 1, 4713 BC mapped to “Universal Time”. I assume they mean UTC and the modern ISO 8601 calendar system. See Wikipedia.
The java.time classes built into Java make this easy.
long input = 2_456_606L;
LocalDate ld = LocalDate.MIN.with ( java.time.temporal.JulianFields.JULIAN_DAY , input );
Dump to console.
System.out.println ( "input: " + input + " is: " + ld );
input: 2456606 is: 2013-11-09
For more discussion, see my Answer on a duplicate Question.
Going the other direction, converting a modern date to a Julian Day.
long output = ld.getLong ( java.time.temporal.JulianFields.JULIAN_DAY );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The Julian date for Nov 18 2013 is "2013322". The number you used, "2456606", would be the 606th day of 2456, which is Aug 28, 2457.
You might also have intended to use a different date format than "yyyyD" for your input. See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html for information on possible codes.
Edit
The value that you used for the Julian date is the number of days since January 1, 4713 BCE. To get the Julian date using that system, you'll need to do something like the following:
String j = "2456606";
int day = Integer.parseInt(j) - x; // x == Jan 1, 1970 on the Gregorian
j = Integer.toString(day);
Date date = new SimpleDateFormat("D").parse(j);
String g = new SimpleDateFormat("dd.MM.yyyy").format(date);
System.out.println(g);
Where x is the Julian day corresponding to Jan 1, 1970 on the Gregorian calendar, i.e., the number of days elapsed between January 1, 4713 BCE and Jan 1, 1970.
If you have 7 digit julian date then you can use the following to convert it to Gergorian date.
The longJuliandate is your input and it'd return a String, which you can format for Date. You'd need to use "yyDDD" if you've 5 digit Julian date.
DateFormat dt = new SimpleDateFormat("yyyyDDD");
try
{
Date date = dt.parse(longJulianDate); //2018038
String str = new SimpleDateFormat("yyyyMMdd").format(date);
} catch (ParseException e) {}
Related
I used a calander and add one minute to it each time. but in date "2017-9-21 23:59" something strange happent. The date come one hour back. It's behavior is like date saving time, but that time date saving must not happent.
here is my code and output:
GregorianCalendar fromCalendar = new GregorianCalendar(2017, 8, 21, 22, 58);
for (int i = 0; i < 120; i++) {
System.out.println(fromCalendar.get(Calendar.YEAR) + "-"
+ (fromCalendar.get(Calendar.MONTH) + 1) + "-" + fromCalendar.get(Calendar.DAY_OF_MONTH) + " "
+ fromCalendar.get(Calendar.HOUR_OF_DAY) + ":" + fromCalendar.get(Calendar.MINUTE) + " ");
fromCalendar.add(Calendar.MINUTE, 1);
}
Output:
.
.
.
2017-9-21 23:58
2017-9-21 23:59
2017-9-21 23:0
2017-9-21 23:1
2017-9-21 23:2
.
.
.
Is there any simple point I misunderstood about it?
According to the TimeAndDate.com DST page there is only ONE country in the world where the DST changeover happened at 00:00 on 2017/09/22: Iran
Therefore you must be using the timezone for Iran: Asia/Tehran.
The Answer by Jim Garrison is correct and should be accepted. You are apparently seeing a Daylight Saving Time cut-over for a time zone such as Asia/Tehran.
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Specify a time zone using ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Tehran" ) ; // Testing the Daylight Saving Time cut-over in Iran.
ZonedDateTime zdt1 = ZonedDateTime.of( 2017 , 9 , 21 , 23 , 59 , 0 , 0 , z ); // Set the moment to what might *appear* be the minute before midnight but is not, is actually an hour and a minute before midnight.
ZonedDateTime zdt2 = zdt1.plusMinutes( 1 ); // Adding a minute takes us to 11 PM again, but with a different offset-from-UTC, for a 25-hours long day.
Dump to console.
System.out.println( "zdt1: " + zdt1 );
System.out.println( "zdt2: " + zdt2 );
See this code run live at IdeOne.com.
zdt1: 2017-09-21T23:59+04:30[Asia/Tehran]
zdt2: 2017-09-21T23:00+03:30[Asia/Tehran]
Notice how adding a minute to roll-over midnight sent us back to 11 PM on the same date but with a different offset-from-UTC, 03:30 versus 04:30. So the 21st of September 2017 in Iran ran 25 hours long.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Hello I'm trying to convert a string in the format "17:50" to a date in android but when I try to run this code I get the correct hour from the string but the full date is from 1970. I need this date to schedule some local notifications on a given time of the day or in the next day.
String dtStart = "17:50";
SimpleDateFormat format = new SimpleDateFormat("H:mm");
try {
Calendar cal = Calendar.getInstance();
Date date = format.parse(dtStart);
cal.setTime(date);
System.out.println(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
Thu Jan 01 17:50:00 BRT 1970
It's not an error, your code works well. Just if you want to get current date, you have to add the difference between current day and 1st of January 1970.
Your parsed date gives you 17:30 hours, which means 17 * 60 * 60 * 1000 ms + 30 * 60 + 1000 ms.
This way you can find current day: https://stackoverflow.com/a/1908419/4142087
What Anton suggested was correct, and the current day / next day logic is your custom implementation. You have to check current time and if it past that time, jump to setting up the alarm the next day.
java.time
You need a time-of-day class to represent your intended meaning. The legacy date-time classes from the earliest versions of Java lack such a class. The java.sql.Time class pretends to do this, but actually contains a date as well due to poor design decisions.
LocalTime
You want the LocalTime class for a time-of-day value without a date and without a time zone.
It uses a generic 24-hour single-day clock. Adding/subtracting spans of time wraps around the clock since it lacks any concept of dates.
Define a formatting pattern to match your input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "H:mm" ) ; // Uppercase `H` means 24-hour clock, lowercase `h` means 12-hour clock.
Parse input string.
String input = "7:50" ;
LocalTime lt = LocalTime.parse( input , f ) ;
Generate a string in standard ISO 8601 format.
String output = lt.toString() ;
07:50
Perhaps your business logic requires assigning the time-of-day to a date. To determine a moment, a point on the timeline, you must also specify a time zone.
LocalDate ld = LocalDate.of( 2018 , Month.MARCH , 27 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The ISO-8601 standard states that
"The first week of a year is the week that contains the first Thursday
of the year (and, hence, always contains 4 January)."
Meaning the first week of the year is not that which contains January the 1st but the first one that contains at leat four days into the new year.
Acording to that Mon, January 11 2016 is on week #2. Here is a list of week numbers for 2016.
Ubuntu reflects that in its time widget:
And the cal command does also:
Oracle supports it with the "iw" parameter of TO_CHAR:
> select to_char(to_date('11/01/2016','dd/mm/yyyy'),'iw') weekno from dual;
> WEEKNO
02
But Java says Mon, January 11 2016 is week #3
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
System.out.println(c.get(Calendar.WEEK_OF_YEAR));
Output:
Mon Jan 11 09:02:35 VET 2016
3
Java thinks the first week of the year is the one that contains January the 1st.
- Is there a way for Java to use the ISO-8601-copliant week numbering?
As I noted in my comment, the default behavior is locale specific. Some locales will give 3, some will give 2.
Luckily, you can specify the number of days that has to be present in the first week of the year, for a given Calendar. As you write above, for ISO 8601, this number is 4, thus the following code should work:
Calendar c = Calendar.getInstance();
c.setMinimalDaysInFirstWeek(4); // For ISO 8601
System.out.println(c.getTime());
System.out.println(c.get(Calendar.WEEK_OF_YEAR));
This should make the output correct regardless of locale.
Test output:
Mon Jan 11 14:54:22 CET 2016
2
tl;dr
myZonedDateTime.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR )
…and…
myZonedDateTime.get( IsoFields.WEEK_BASED_YEAR )
Avoid legacy date-time classes
As the correct Answer by haraldK explains, the Calendar class’s definition of week varies by locale. While well-intentioned, this is confusing.
You should be avoiding Calendar and related classes such as Date. They are now supplanted by the java.time classes.
ISO 8601 week
As for ISO 8601 week, be clear that means:
The first day is Monday, running through Sunday.
Week number one of a week-based year contains the first Thursday of the calendar year.
A week-based year has either 52 or 53 weeks.
The first/last few days of a calendar year may appear in the previous/next week-based year.
java.time
The java.time classes include limited support for ISO 8601 standard weeks. Call the get method on various classes such as LocalDate and ZonedDateTime. Pass the TemporalField implementations found as constants in the IsoFields class.
int week = myZonedDateTime.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ;
int weekBasedYear = myZonedDateTime.get( IsoFields.WEEK_BASED_YEAR ) ;
ThreeTen-Extra
Even better, add the ThreeTen-Extra library to your project to use YearWeek class.
org.threeten.extra.YearWeek yw = YearWeek.from( myZonedDateTime ) ;
Beware of calendaring software settings
Never assume the definition of a week number. Be sure the source of such a number has the same definition of week as you, such as ISO 8601 definition.
For example, the Calendar app supplied by Apple with macOS defaults to a "Gregorian" calendar definition of week. As for what that means, I do not know as I could not find any documentation about their intent/definition. For ISO 8601 weeks, you must change a setting away from default.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I've to write a generic code as such, it should give months difference between two dates.
For eg., my input data will be
1. date1 = 22/01/2016
date2 = 30/03/2016
2. date1 = 22/01/2016
date2 = 20/12/2015
based on months difference, I've to move forward(if date2 is future date to date1) or backward(if date2 is past date to date1), those many times.
You could simply compare these two dates as stated here
According to the result you just have to call the same code as if you have clicked on the button yourself (just call the respective mehtod (if you don't use a method for that I would advise you to do so))
Greetings Raven
EDIT:
The difference betweent two dates can be calculated like this
Calendar data = Calendar.getInstance();
Calendar data2 = Calendar.getInstance();
int diff =(int) Math.round(( (data2.getTimeInMillis() - data.getTimeInMillis()) /* ms*/
/ 1000.0 /* seconds*/
/ 3600.0 /*hours*/
/ 24.0 /*days*/
/ 30.0 ))/* monts*/;
With Math.round you ensure months of 31 and 28 days return the right value
Replace data and data2 for your own values
tl;dr
Period.between(
LocalDate.of( 2016 , Month.JANUARY , 22 ) ,
LocalDate.of( 2016 , Month.MARCH , 30 )
).isNegative()
Details
Your Question is not clear, but this might help point you in the right direction.
Avoid the troublesome old date-time classes such as Date that are now legacy, supplanted by the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
date1 = 22/01/2016
date2 = 30/03/2016
LocalDate start = LocalDate.of( 2016 , Month.JANUARY , 22 ) ;
LocalDate stop = LocalDate.of( 2016 , Month.MARCH , 30 ) ;
Period
Calculate the number of days, months, and years elapsed as a Period.
Period period = Period.between( start , stop ) ;
Test if the stop comes before the start, meaning the elapsed time is negative, going backwards along the timeline.
Boolean isTimeGoingBackwards = period.isNegative() ;
Months
Your comments mention getting a number of months. Understand multiple ways to count months:
Count days elapsed, divided by 30 as the length of a generic month.
Count of calendar months completely covered
Count of calendar months touched by the span of time
Java offers at least some of these. Read the documentation to decide which meets your needs. If going backwards in time, the resulting number is negative.
ChronoUnit.MONTHS
long months = ChronoUnit.MONTHS.between( start , stop ) ;
Period.toTotalMonths
int months = Period.between( start , stop ).toTotalMonths() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I am trying to get day ,month and year from a Julian date.
String date = "13136";//Julian date
Date convertedDate = new SimpleDateFormat("yyDDD").parse(date);
System.out.println(convertedDate);
It prints
Thu May 16 00:00:00 BST 2013
which is correct.
Now I want to get Day , Month and Year from it
Calendar cal = Calendar.getInstance();
cal.setTime(convertedDate);
System.out.println(cal.get(Calendar.MONTH));
It prints 4 .
It should print 5 instead of 4 . Why is it not printing as correct ? What I have done wrong here?
As per the javadoc of Calendar.MONTH:
Field number for get and set indicating the month. This is a
calendar-specific value. The first month of the year in the Gregorian
and Julian calendars is JANUARY which is 0; the last depends on the
number of months in a year.
So months starts from zero so your output 4 is correct, for general usecase in your code it would be safe to add 1 to it unless you use this values as MONTH value in Calendar again.
As the javadocs state, months begin at zero: 0 = January, 1 = February, and so on.
tl;dr
LocalDate.parse (
"13136",
DateTimeFormatter.ofPattern ( "uuDDD" )
).getMonthValue()
5
…for month of May 2013.
Ordinal, not Julian
Your use of the word “Julian” is technically incorrect, though common. Folks seem to confuse day-of-year (1-365 or 1-366) with practice of counting the number of days elapsed since January 1, 4713 BC used in some scientific fields.
The terms “ordinal date” or day-of-year are more clear.
ISO 8601
Your format for ordinal dates is not standard. Whenever possible, use the standard ISO 8601 formats:
YYYY-DDD
YYYYDDD
java.time
The modern way is with the java.time classes that supplant the troublesome old legacy date-time classes.
DateTimeFormatter
Note that the formatting pattern codes in DateTimeFormatter class are similar to the legacy class but not exactly the some.
String input = "13136"; //Julian date
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuDDD" );
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate localDate = LocalDate.parse ( input, f );
Dump to console.
System.out.println ("localDate: " + localDate );
localDate: 2013-05-16
Month
You can ask about the month of that LocalDate. The Month enum pre-defines a dozen objects, one for each month of the year. And unlike the crazy legacy classes, these are sanely numbered 1-12 for January-December.
If you are passing the month number around your code, I suggest you instead pass around these enum objects. Doing so gives you type-safety, valid values, and self-documenting code.
Month month = localDate.getMonth();
You can get the localized name of that month if needed.
String output = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ); // Or Locale.US, Locale.ITALY, whatever.
If you truly do need the number of the month 1-12, ask in either way.
int monthNumber = month.getValue() ;
int monthNumber = localDate.getMonthValue() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.