I have stored date in a string. Now I want to get minutes from the date string. How can I convert it into minutes?
Here is how I stored in a class:
public String fromDate;
public String toDate;
I have set getter and setter methods. I have saved the date value now I want to retrive the value and convert to minutes.
Retriving Like this:
Calendar c = Calendar.getInstance();
String datefrom = eventData.getFromDate();
I tried using this calendar instance:
c.set(Calendar.HOUR, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.DATE,day);
Date datefrom = c.getTime();
startTime = String.valueOf(datefrom);
int hour = c.get(Calendar.HOUR);
int totalMinutes = hour * 60;
But this I can get from Date object. I have stored date in String format. How can I convert this?
Use Joda-Time:
String fromDate;
String toDate;
DateTimeFormatter format = new DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime fromDT = format.parseDateTime(fromDate);
DateTime toDT = format.parseDateTime(toDate);
Duration duration = new Duration(fromDT, toDT);
int minutes = duration.getStandardMinutes();
To import in Android Studio, update your build.gradle file:
apply plugin: 'android'
dependencies {
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.2'
}
To convert a String to Date in Java you would have to use the DateFormat like the sample below:
String string = "January 26, 2016";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Tue Jan 26 00:00:00 GMT 2016
then you can go ahead with your Calendar implementation.
Usually i'd suggest to parse the time with a SimpleDateFormat, but I think in this case (since the dates seem to have a defined form and there might be problems with the timezones) i'll suggest to retrieve the information yourself:
String date = "Wed Jan 27 07:25:29 GMT+05:30 2016";
String[] times = date.substring(11, 16).split(":");
int minutes = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
System.out.println(minutes);
The part date.substring(11, 16) extracts the hours and minutes part from the string ("07:25").
The part .split(":"); splits the string "07:25" into two strings: "07" and "25".
after that you just parse those numbers to integers with Integer.parseInt(...) and calculate the number of minutes!
To get the minutes from a String is possible to use a DateFormat to convert the string to a Date and after use your code.
Your Question is really two questions:
How to parse a String to get a date-time object
How to get number of minutes since start-of-day from a date-time object
The first one, parsing a String into a date-time, has been covered at least 1,845 times on Stack Overflow, so I will skip it. The second Question is addressed below.
Please try to make your questions more clear. And focus on a single topic as narrowly as possible, as that is the intention for Stack Overflow.
Minutes-Of-Day
What you seem to want is called “Minutes-Of-Day”, the number of minutes since the start of the day.
Be careful and thoughtful here as there are two different definitions for minutes-of-day. You can get the actual number of minutes for a specific day in a specific time zone. Or you can calculate for a generic 24-hour day. Because of Daylight Saving Time (DST) and other anomalies, a day is not necessarily 24 hours long. For example, in most of the United States the use of DST means a day may be 23, 24, or 25 hours long.
The Question’s code and other Answers ignore the crucial issue of time zone (a common mistake in date-time work). If you do not specify a time zone, your JVM’s current default time zone is silently applied. Not good… that default can change at any moment, even during runtime! Better to always specify the time zone you expect/desire.
Avoid Old Date-Time Classes
The old date-time classes bundled with the earliest versions of Java are notoriously troublesome. Avoid them. Instead use the java.time framework built into Java 8 and later (see Tutorial). If that technology is not available to you, use the Joda-Time library (which inspired java.time). Examples below are in java.time in Java 8 Update 66.
java.time
Let’s look at March 3rd, 2015. This day was the "Spring ahead" DST changeover day for most of the United States. The clock jumped from 2 AM to 3 AM. So 03:00:00.0 on this day meant two hours (120 minutes) actually elapsed since the start of the day. If we treat this as a generic 24-hour day, we would say three hours (180 minutes) elapsed. The java.time classes can calculate minutes-of-day in both definitions.
First we get 3 AM on that changeover day. We use one of the time zones which recognized DST.
ZoneId zoneId = ZoneId.of ( "America/Los_Angeles" );
ZonedDateTime zdt = ZonedDateTime.of ( 2015 , 3 , 8 , 3 , 0 , 0 , 0 , zoneId );
Generic 24-Hour Day
Next we get the minutes since start of day assuming a generic 24-hour day. The ChronoField enum provides many ways to access TemporalField values such as MINUTE_OF_DAY.
long minutesOfDayForGeneric24HourDay = zdt.get ( ChronoField.MINUTE_OF_DAY );
Actual Day
To get the actual number of minutes elapsed since the start of this particular day for this particular time zone in which DST was changing over, we must do a bit more work. We have to determine the first moment of the day from which we can calculate elapsed time. To get that first moment, we must go through the LocalDate class which is a date-only value without time-of-day nor time zone. On that LocalDate object we call atStartOfDay to adjust back into a date-time value (a ZonedDateTime). You might think you could skip this by assuming the day starts at 00:00:00.0 but that is not always true.
ZonedDateTime zdtStart = zdt.toLocalDate ().atStartOfDay ( zoneId );
Now calculate elapsed time. The Duration class represents a span of time as hours, minutes, and seconds. From that Duration we can ask the total number of minutes, converting hours to minutes.
Duration duration = Duration.between ( zdtStart , zdt );
long minutesOfDayForActualDay = duration.toMinutes ();
Dump to console. Note how the generic ChronoField approach says 180 minutes while the actual Duration approach yields 120 minutes.
System.out.println ( "zdt: " + zdt + " | minutesOfDayForGeneric24HourDay: " + minutesOfDayForGeneric24HourDay + " | duration: " + duration + " | minutesOfDayForActualDay: " + minutesOfDayForActualDay );
zdt: 2015-03-08T03:00-07:00[America/Los_Angeles] | minutesOfDayForGeneric24HourDay: 180 | duration: PT2H | minutesOfDayForActualDay: 120
Related
From the front end I am receiving a separate LocalDate (variable name is date), along with separate Integers for hours, minutes, seconds, and an "AM" or "PM" String, and I need to combine these into a java.time.Instant object to store in the database. I tried to construct a LocalTime as follows, adding 12 hours if this is a PM time and then constructing an Instant:
LocalTime time = LocalTime.of("pm".equals(amPm) ? hours + 12: hours, minutes, seconds);
Instant instant = date.atTime(time).toInstant(ZoneOffset.UTC);
But when I store and reload the page, though the date is always intact, the time is always being changed. If I set the date to 1/29/1900 and the time to 07:01:01 AM, the Instant I am creating and storing has the value: 1900-01-29T07:01:01Z when I debug, which appears correct, but when the page reloads, the time says 02:01:01 AM, and that is the time that is stored in the database.
Am I constructing the time or the instant incorrectly?
There’s hardly any doubt that your unexpected observations are due to one or more time zone issues.
So the first thing you need to do is make sure you know which time zones are involved.
Which time zone is your front end using for sending date and time to you?
Which time zone is your database using for storing the date and time and displaying them to you when you check them? (UTC would be recommended for storing the times.)
Once you know this you can check:
Is the conversion from 1/29/1900 07:01:01 AM from the front end in some time zone to an Instant of 1900-01-29T07:01:01Z correct? The Instant displays its time in UTC (denoted by the trailing Z).
Is the conversion from the Instant to 02:01:01 AM in the database time zone correct?
Is the time being fetched correctly from the database? I am assuming you are fetching it back into Java?
Is the time you’ve got in Java being converted correctly to 02:01:01 AM on the front end? Again I am assuming that on page reload your are displaying the time fetched from the database, but I don’t think you have told us, so I could be wrong.
To answer your question:
Am I constructing the time or the instant incorrectly?
It depends; it’s certainly possible.
Your construction of the time is assuming that pm is always in lower case and that 12 o’clock (midnight or noon) is given as 0. On one hand I find both assumptions more or less unlikely, on the other hand they cannot account for the discrepancy of 5 hours that you observed. 12 would conventionally be given as 12 (not 0) on a 12 hour clock. And your question gives PM in upper case.
Your construction of the Instant assumes that the front end sent the time in UTC. To me this sounds unlikely too, and it may be the reason or one of the reasons why you observed an incorrect time being displayed back after page reoload.
Code example
In the following snippet I am making the opposite assumptions: 12 is given as 12, AM/PM may be in any case, and the front end time zone is America/New_York. It’s probably way off, but there may be a detail that you can pick and use for your purpose.
DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive() // Accept all of am, AM, aM and Am
.appendPattern("h:m:sa")
.toFormatter(Locale.US);
ZoneId zone = ZoneId.of("America/New_York");
LocalDate date = LocalDate.of(1900, Month.JANUARY, 29);
int hours = 7;
int minutes = 1;
int seconds = 1;
String amPm = "AM";
String constructedTimeString
= "" + hours + ':' + minutes + ':' + seconds + amPm;
LocalTime time = LocalTime.parse(constructedTimeString, timeFormatter);
Instant instant = date.atTime(time).atZone(zone).toInstant();
System.out.println(instant);
Output is:
1900-01-29T12:01:01Z
Geeky section: avoiding formatting time into a string and parsing it back
I couldn’t help thinking about whether it would be possible to have java.time parse the AM/PM string without having to construct a string for the time of day and parse it. It is possible, but we need to use the low-level TemporalAccessor interface, which is otherwise usually unnecessary.
DateTimeFormatter amPmFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive() // Accept all of am, AM, aM and Am
.appendPattern("a")
.toFormatter(Locale.US);
int hours = 7;
int minutes = 1;
int seconds = 1;
String amPm = "AM";
TemporalAccessor parsedAmPm = amPmFormatter.parse(amPm);
LocalTime time = LocalTime.of(0, minutes, seconds)
.with(ChronoField.AMPM_OF_DAY, parsedAmPm.get(ChronoField.AMPM_OF_DAY))
.with(ChronoField.CLOCK_HOUR_OF_AMPM, hours);
System.out.println(time);
07:01:01
Construction of the Instant proceeds as before.
In my application I retrieve from a webservice an unix timestamp (between 0 and 15minutes in the future) and I display a countdown to that time in the form of XXm-XXs.
So I simply do System.currentTimeMillis() - timestamp and I convert the result in a human readable date.
Everything works fine but it seems that with certain timezones, my timer is 30 minutes off, because System.currentTimeMillis() return a value 1800000 millis lower than expected because Calendar returns wrong value of minutes when I request minutes with it.
The timezone is the GMT+8 of Kuala Lumpur (Malasya). Using another GMT+8 timezone works normally.
Example:
long till = requestTimeFromWebService()
long now=System.currentTimeMillis();
long remaining_time = till - now;
Calendar c=Calendar.getInstance();
c.setTimeInMillis(remaining_time);
int minutes=c.get(Calendar.MINUTE);
System.out.println(""+minutes+"m");
int seconds=c.get(Calendar.SECOND);
System.out.println(""+seconds+"s");
With this code System.out.println(""+minutes+"m"); prints (e.g) 5m if GMT+2 Rome Timezone is set and 35m if GMT+8 Kuala Lumpur Timezone is set.
Is this a known bug?
I found this: http://www.objectdb.com/database/forum/363 that seems to confirm an issue.
I also found this: https://en.wikipedia.org/wiki/Time_in_Malaysia
Blockquote At 2330 hrs local time of 31 December 1981, people in Peninsular Malaysia adjusted their clocks and watches ahead by 30 minutes to become 00:00 hours local time of 1 January 1982, to match the time in use in East Malaysia, which is UTC+08:00.
This could explain where the bug comes off.
Any advice?
A date-time != span-of-time
You are abusing the date-time class java.util.Calendar (or java.util.Date) to inappropriately track a span of time. That class tracks time as a count of milliseconds since the epoch of start of 1970 in UTC (1970-01-01T00:00:00Z) plus an assigned time zone.
So when you instantiate with a count of milliseconds of 5 minutes, you are actually creating a date-time of 5 minutes after start of 1970, 1970-01-01T00:05:00Z for a java.util.Date and adding a time zone for java.util.Calendar.
When you applied a time zone for Malaysia you end up getting the old-style Malaysia time rules for 1970, not today’s post-1981 Malaysia rules.
So, no bugs, just a misuse of features.
Lesson learned: Do not use a date-time value to represent a span-of-time.
java.time
Another problem: You are using the notoriously troublesome old legacy date-time classes, now supplanted by the java.time classes.
If by “unix timestamp” you meant a count of milliseconds from an epoch of 1970 in UTC such as 1_473_738_754_764L, then use the Instant class. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
First, we simulate some input data as described in Question as being in the future up to 15 minutes.
Instant instantNow = Instant.now ();
long seconds = TimeUnit.MINUTES.toSeconds ( 10 );
String input = Long.toString ( instantNow.plusSeconds ( seconds ).toEpochMilli () ); // 10 minutes in the future.
To process that String input, we convert to a long primitive value, and feed it to a Instant factory method.
Instant instantLater = Instant.ofEpochMilli ( Long.valueOf ( input ) );
Span-of-time
To capture the elapsed time, use the Duration class.
Duration duration = Duration.between ( instantNow , instantLater );
System.out.println ( "instantNow: " + instantNow + " | instantLater: " + instantLater + " | duration: " + duration );
When run. Note the standard ISO 8601 format for a duration PnYnMnDTnHnMnS where P marks the beginning and the T separates the years-months-days portion from the hours-minutes-seconds portion. So PT10M is “ten minutes”. Always use this format for textual representation of elapsed time rather than ambiguous clock-style (HH:MM:SS). The Duration and Period classes in java.time can parse and generate such strings directly with no need to specify a formatting pattern.
instantNow: 2016-09-13T19:16:33.913Z | instantLater: 2016-09-13T19:26:33.913Z | duration: PT10M
Note that none of the above code cared about time zones. All the values were in UTC. Much of your business logic, data storage, and data exchange should be in UTC. Only use zoned values where necessary or for presentation to the user.
Zoned
Your Questions asked about zoned values for Rome and for Malaysia. Apply a ZoneId to get a ZonedDateTime. Specify a proper time zone name. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId zMontreal = ZoneId.of ( "America/Montreal" );
ZoneId zRome = ZoneId.of ( "Europe/Rome" );
ZoneId zKualaLumpur = ZoneId.of ( "Asia/Kuala_Lumpur" );
ZonedDateTime zdtMontreal = instantNow.atZone ( zMontreal );
ZonedDateTime zdtRome = instantNow.atZone ( zRome );
ZonedDateTime zdtKualaLumpur = instantNow.atZone ( zKualaLumpur );
System.out.println ( "instantNow: " + instantNow + " | zdtMontreal: " + zdtMontreal + " | zdtRome: " + zdtRome + " | zdtKualaLumpur: " + zdtKualaLumpur );
instantNow: 2016-09-13T20:23:34.280Z | zdtMontreal: 2016-09-13T16:23:34.280-04:00[America/Montreal] | zdtRome: 2016-09-13T22:23:34.280+02:00[Europe/Rome] | zdtKualaLumpur: 2016-09-14T04:23:34.280+08:00[Asia/Kuala_Lumpur]
While I still don't know why the original code doesn't work, I can resolve my specific problem simply using
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
instead than
Calendar c=Calendar.getInstance();
So I can always compare timestamp with the UTC TimeZone that is what I'm interested in.
Btw, Calendar should work in my case even setting the locale timezone (that is what happens when no argument is passed to getInstance()), and it does for most of the timezones, but apparently not for everyone.
Writing a Java application that takes user input into a Time and Date class, but I am not sure how to take this user input and convert it into Universal and Standard time... I have spent multiple hours surfing the web and stack overflow and have not been able to find a solution.
I have hours, minutes, seconds, year, month, day all in separate integer variables and need to display them in Universal and Standard time.
Thanks for taking a look...
There are two solutions:
first is place all of input in the string and parse it:
String dateStr = ""
//put your input in this string in some format/ example:
//dateSttr = year + "." + month + "." + day + " " + hour + ":" + minute;
//It is better to use StringBuilder
DateFormat inputFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm");
//note that hh is 12h-format and HH is 24h-format
DateFormat outputFormat1 = new SimpleDateFormat("your_outputFormat");
DateFormat outputFormat2 = new SimpleDateFormat("your_another_outputFormat");
Date date = inputFormat.parse(dateStr);
String o1, o2;
o1 = outputFormat1.format(date);
o2 = outputFormat2.format(date);
//o1 and o2 is your result.
For the rules, how this formats is done, see javadoc
The second solution is to get a new date and set your parameters:
Calendar cln = Calendar.getInstance().clear();
//by default you get a calendar with current system time
//now set the fields. for example, day:
cln.set(Calendar.YEAR, 2015);
cln.set(Calendar.MONTH, Calendar.FEBRUARY);
cln.set(Calendar.DAY_OF_MONTH, 17);
cln.set(Calendar.HOUR_OF_DAY, 18);//Calendar.HOUR for 12h-format
cln.set(Calendar.MINUTE, 27);
See more about setting calendar in javadoc
Note, that in the second variant, you might have some fields undefiend.
If #JonSkeet 's assumption and mine is correct, you're starting with either UTC or your local time. Displaying it is just a matter of formatting your output.
For the other type of time, you add or subtract a number of hours, which you can find on the web. The tricky part is that this may push you into the next calendar day, or pull you back into the previous one. To deal with that, I figure you want to either
implement an adder for year, month, day, hour--or
convert those to decimal somethings (Excel uses days, for instance, where as I write this it's 42328.08813), shift the value by the appropriate number of hours, and convert it back.
java.time
The Answer by TEXHIK is correct, but outdated. Also, as others mentioned, I do not know what you mean by "Universal and Standard time". But I'll try to get you part way there.
As of Java 8, the old java.util.Date/.Calendar classes have been supplanted by the new java.time framework. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The ZonedDateTime class has a factory method taking numbers for year, month, and so on.
Plus you must specify a time zone. If your numbers represent a date-time in UTC, use the ZoneOffset.UTC constant. For other time zones, specify a ZoneId object by using a proper time zone name; never use the 3-4 letter codes such as EST or IST as their are neither standardized nor unique.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
// ZoneId zoneId = ZoneOffset.UTC; // ZoneOffset is a subclass of ZoneId.
ZonedDateTime zdt = ZonedDateTime.of( 2015 , 1 , 2 , 3 , 4 , 5 , 6 , zoneId );
zdt: 2015-01-02T03:04:05.000000006-05:00[America/Montreal]
You can convert to UTC or another time zone.
ZonedDateTime zdt_Kolkata = zdt.withZoneSameInstant ( ZoneId.of("Asia/Kolkata") );
ZonedDateTime zdt_Utc = zdt.withZoneSameInstant ( ZoneOffset.UTC );
zdt_Kolkata: 2015-01-02T13:34:05.000000006+05:30[Asia/Kolkata]
zdt_Utc: 2015-01-02T08:04:05.000000006Z
If working with classes not yet updated for java.time, convert to a java.util.Date. First extract a Instant object, a moment on the timeline always in UTC.
java.util.Date date = java.util.Date.from ( zdt.toInstant () );
I don't need a whole story to clarify my question, so I'll just show the code (which is a mere example). How come there is a difference in my result?
Code
long millis = 2305293L;
System.out.println(
millis + "ms = " +
(millis / 1000) + "s = " +
(millis / 1000 / 60) + "m");
System.out.println(
new SimpleDateFormat("HH:mm:ss").
format(
new Date(millis)
)
);
Output
2305293ms = 2305s = 38m
01:38:25
If you are in London, or Paris, the timezone was GMT+1 on 1 Jan 1970.
For reasons #ARC explains in the comments, the UK used GMT+1 or UTC+1 from 18 Feb 1968 to 31 Oct 1971
is it possible for me to convert a long without any timezones interfering?
Set the TimeZone to be GMT.
long millis = 2305293L;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date(millis)));
prints
00:38:25.293
Try this :
System.out.println(new java.util.Date (0));
you will see it begins at 01:00:00, hence the difference of one hour.
The other answers are correct and were good answers when the question was asked in 2013. Today we should no longer use Date nor SimpleDateFormat, so I would like to show you a couple of modern code snippets instead. The correct way to format your (in this case) 2 305 293 milliseconds depends on what they represent. I am presenting three options for three different situations.
Formatting a number of milliseconds since the epoch
You need to decide in which time zone you want to interpret your point in time. For example:
long millis = 2_305_293L;
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.ENGLISH);
ZonedDateTime dateTime = Instant.ofEpochMilli(millis)
.atZone(ZoneId.of("America/Coral_Harbour"));
String formattedTime = dateTime.format(formatter);
System.out.println(formattedTime);
December 31, 1969 at 7:38:25 PM EST
Since at the epoch Coral Harbor was at UTC offset -05:00, we get a time near the end of 1969. If you want the time in UTC (since the epoch is defined in UTC; in other words, if you want 00:38:25), it’s a bit different:
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.ENGLISH);
OffsetDateTime dateTime = Instant.ofEpochMilli(millis)
.atOffset(ZoneOffset.UTC);
Jan 1, 1970, 12:38:25 AM
In addition to time zone you may vary the language through the locale and the length of the format through the format style (full, long, medium, short). If you want the time of day without the date, use ofLocalizedTime instead of ofLocalizedDateTime.
Formatting a millisecond of day
Assuming your milliseconds are since 0:00 (“midnight”) in whatever time zone:
LocalTime time = LocalTime.MIN.with(ChronoField.MILLI_OF_DAY, millis);
System.out.println(time);
00:38:25.293
If this format is satisfactory, you don’t need any explicit formatter. If not, you may use a DateTimeFormatter.
Formatting a duration, an amount of time
An amount of time is a completely different thing from a time and is handled as a Duration object. There is no direct support for formatting it, but since Java 9 it’s not so hard (when you know how):
Duration amountOfTime = Duration.ofMillis(millis);
String formattedTime = String.format("%02d:%02d:%02d",amountOfTime.toHours(),
amountOfTime.toMinutesPart(), amountOfTime.toSecondsPart());
System.out.println(formattedTime);
00:38:25
Link
Oracle tutorial: Date Time explaining how to use java.time.
I have list with long values (for example: 1220227200, 1220832000, 1221436800...) which I downloaded from web service. I must convert it to Dates. Unfortunately this way, for example:
Date d = new Date(1220227200);
returns 1 Jan 1970. Anyone know another way to convert it correctly?
The Date constructor (click the link!) accepts the time as long in milliseconds, not seconds. You need to multiply it by 1000 and make sure that you supply it as long.
Date d = new Date(1220227200L * 1000);
This shows here
Sun Aug 31 20:00:00 GMT-04:00 2008
tl;dr
java.time.Instant // Represent a moment as seen in UTC. Internally, a count of nanoseconds since 1970-01-01T00:00Z.
.ofEpochSecond( 1_220_227_200L ) // Pass a count of whole seconds since the same epoch reference of 1970-01-01T00:00Z.
Know Your Data
People use various precisions in tracking time as a number since an epoch. So when you obtain some numbers to be interpreted as a count since an epoch, you must determine:
What epoch?Many epochs dates have been used in various systems. Commonly used is POSIX/Unix time, where the epoch is the first moment of 1970 in UTC. But you should not assume this epoch.
What precision?Are we talking seconds, milliseconds, microseconds, or nanoseconds since the epoch?
What time zone?Usually a count since epoch is in UTC/GMT time zone, that is, has no time zone offset at all. But sometimes, when involving inexperienced or date-time ignorant programmers, there may be an implied time zone.
In your case, as others noted, you seem to have been given seconds since the Unix epoch. But you are passing those seconds to a constructor that expects milliseconds. So the solution is to multiply by 1,000.
Lessons learned:
Determine, don't assume, the meaning of received data.
Read the doc.
Your Data
Your data seems to be in whole seconds. If we assume an epoch of the beginning of 1970, and if we assume UTC time zone, then 1,220,227,200 is the first moment of the first day of September 2008.
Joda-Time
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use instead either the Joda-Time library or the new java.time package bundled in Java 8 (and inspired by Joda-Time).
Note that unlike j.u.Date, a DateTime in Joda-Time truly knows its own assigned time zone. So in the example Joda-Time 2.4 code seen below, note that we first parse the milliseconds using the default assumption of UTC. Then, secondly, we assign a time zone of Paris to adjust. Same moment in the timeline of the Universe, but different wall-clock time. For demonstration, we adjust again, to UTC. Almost always better to explicitly specify your desired/expected time zone rather than rely on an implicit default (often the cause of trouble in date-time work).
We need milliseconds to construct a DateTime. So take your input of seconds, and multiply by a thousand. Note that the result must be a 64-bit long as we would overflow a 32-bit int.
long input = 1_220_227_200L; // Note the "L" appended to long integer literals.
long milliseconds = ( input * 1_000L ); // Use a "long", not the usual "int". Note the appended "L".
Feed that count of milliseconds to constructor. That particular constructor assumes the count is from the Unix epoch of 1970. So adjust time zone as desired, after construction.
Use proper time zone names, a combination of continent and city/region. Never use 3 or 4 letter codes such as EST as they are neither standardized not unique.
DateTime dateTimeParis = new DateTime( milliseconds ).withZone( DateTimeZone.forID( "Europe/Paris" ) );
For demonstration, adjust the time zone again.
DateTime dateTimeUtc = dateTimeParis.withZone( DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeParis.withZone( DateTimeZone.forID( "America/Montreal" ) );
Dump to console. Note how the date is different in Montréal, as the new day has begun in Europe but not yet in America.
System.out.println( "dateTimeParis: " + dateTimeParis );
System.out.println( "dateTimeUTC: " + dateTimeUtc );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
When run.
dateTimeParis: 2008-09-01T02:00:00.000+02:00
dateTimeUTC: 2008-09-01T00:00:00.000Z
dateTimeMontréal: 2008-08-31T20:00:00.000-04:00
java.time
The makers of Joda-Time have asked us to migrate to its replacement, the java.time framework as soon as is convenient. While Joda-Time continues to be actively supported, all future development will be done on the java.time classes and their extensions in the ThreeTen-Extra project.
The java-time framework is defined by JSR 310 and built into Java 8 and later. The java.time classes have been back-ported to Java 6 & 7 on the ThreeTen-Backport project and to Android in the ThreeTenABP project.
An Instant is a moment on the timeline in UTC with a resolution of nanoseconds. Its epoch is the first moment of 1970 in UTC.
Instant instant = Instant.ofEpochSecond( 1_220_227_200L );
Apply an offset-from-UTC ZoneOffset to get an OffsetDateTime.
Better yet, if known, apply a time zone ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
It looks like your longs are seconds, and not milliseconds. Date constructor takes time as millis, so
Date d = new Date(timeInSeconds * 1000);
Only set the time in mills on Calendar object
Calendar c = Calendar.getInstance();
c.setTimeInMillis(1385355600000l);
System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.DAY_OF_MONTH));
// get Date
System.out.println(c.getTime());
Those are probably timestamps in seconds and not in milliseconds which is required for the java new Date(long) constructor. Just multiply them by 1000 and you should be allright.
The long values, most likely, correspond to Epoch timestamps, and the values are:
1220227200 = Mon, 01 Sep 2008 00:00:00 GMT
1220832000 = Mon, 08 Sep 2008 00:00:00 GMT
1221436800 = Mon, 15 Sep 2008 00:00:00 GMT
One can convert these long values to java.util.Date, taking into account the fact java.util.Date uses millisecs – as previously hinted, but with some flaw - like this:
// note: enforcing long literals (L), without it the values would just be wrong.
Date date = new Date(1220227200L * 1000L);
Now, to display the date correctly, one can use java.text.DateFormat as illustrated hereafter:
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Wrong date time value: " + date);
System.out.println("Correct date time value: " + df.format(date));
Below are the results of displaying the converted long value to java.util.Date without
using and using the DateFormat:
Date wrong (off by 2 hours): Mon Sep 01 02:00:00 CEST 2008
Correct date : Monday, 1 September 2008 00:00:00 o'clock UTC
Try this:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1220227200 * 1000);
System.out.println(cal.getTime());
Try this with adjusting the date format.
long longtime = 1212580300;
SimpleDateFormat dateFormat = new SimpleDateFormat("MMddyyHHmm");
Date date = (Date) dateFormat.parseObject(longtime + "");
System.out.println(date);
Note: Check for 24 hours or 12 hours cycle.
1220227200 corresponds to Jan 15 1980 (and indeed new Date(1220227200).toString() returns "Thu Jan 15 03:57:07 CET 1970"). If you pass a long value to a date, that is before 01/01/1970 it will in fact return a date of 01/01/1970. Make sure that your values are not in this situation (lower than 82800000).
New Date(number) returns a date that's number milliseconds after 1 Jan 1970. Odds are you date format isn't showing hours, minutes, and seconds for you to see that it's just a little bit after 1 Jan 1970.
You need to parse the date according to the correct parsing routing. I don't know what a 1220227200 is, but if it's seconds after 1 JAN 1970, then multiply it to yield milliseconds. If it is not, then convert it in some manner to milliseconds after 1970 (if you want to continue to use java.util.Date).
Works for me. You probably want to multiplz it with 1000, since what you get are the seconds from 1970 and you have to pass the milliseconds from jan 1 1970
Because 1220227200 ms = 338,952 hours.
java.util.Date has constructor new Date(Long milliseconds) - Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
So, in your case just remember 1 sec = 1000 millisec