Convert unix time to week day - java

How can I convert time from unix timestamp to week day? For example, I want to convert 1493193408 to Wednesday.
I tryed code above, but It always shows Sunday..
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408);
String weekday = sdf.format(dateFormat );

Using java.time
The other Answers use the troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Time zone is crucial in determining a date, and therefore getting a day-of-week.
Get an Instant from your count of while seconds since the epoch of 1970 in UTC. Apply a time zone to get a ZonedDateTime. From there extract a DayOfWeek enumerate object. Ask that object to automatically localize to generate a string of its name.
Instant.ofEpochSecond( 1_493_193_408L )
.atZone( ZoneId.of( "America/Montreal" ))
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.US )
For Android, see the ThreeTenABP project for a back-port of most of the java.time functionality.

You need to multiply it by 1000 since Java and Unix time are not the same.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408L * 1000);
String weekday = sdf.format(dateFormat );

You can use a calendar instance because it provides you methods for getting that information:
Date date = new Date(1493193408000L);
Calendar c = Calendar.getInstance();
c.setTime(date);
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(c.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US));

The Date constructor has the following description:
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.
Your timestamp is in seconds, if you multiply by 1000 (to get milliseconds) you get the expected answer:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408000L);
System.out.println(dateFormat);
String weekday = sdf.format(dateFormat);
System.out.println(weekday);
Which prints
Wed Apr 26 09:56:48 CEST 2017
Wednesday

dateFormatStart != dateFormat
You could also check using:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new Date(System.currentTimeMillis());
String weekday = sdf.format(dateFormat);

Here is right code for you:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408 * 1000);
String weekday = sdf.format(dateFormat );
There is documentation for Java date

You can do the same with the new JDK 8 date time classes. Local date and time is calculated using the seconds from Unix Epoch and then it can be formatted with a specific pattern. The conversion to date time takes into account the Zone as well, I have used the default Zone, but it can be modified to use a specific zone.
ZonedDateTime ldt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1493193408), ZoneId.systemDefault());
System.out.println(ldt.format(DateTimeFormatter.ofPattern("EEEE")));

It’s been said already: your problem is your are feeding number seconds since the Unix epoch into a Date when it expects the number of milliseconds (then one would have expected multiplying by 1000 to be simple, but a couple of the other answers got that part wrong).
If you are going to work with dates, times or weekdays in your app, I agree with the answers that recommend that you consider the newer classes in java.time. They are much nicer to work with. Your code will more directly express your intent.
But if you only need the weekday, a dependency on a third party library may be overkill. I still recommend keeping a distance to the oldfashioned classes SimpleDateFormat, Date and Calendar, though. Is there a third option? There certainly is! A simple oneliner, even:
String weekday = String.format(Locale.ENGLISH, "%tA", 1493193408 * 1000L);
This yields Wednesday as desired. You must still be aware that the result depends on your computer’s time zone setting, though.

Related

How to convert getTime() to 'YYYY-MM-DD HH24:MI:SS' [duplicate]

This question already has answers here:
Convert timestamp in milliseconds to string formatted time in Java
(10 answers)
Closed 5 years ago.
I Have the following code in my application
System.out.println(rec.getDateTrami().getTime());
I need to convert the following format (I suppose that they are seconds)
43782000
29382000
29382000
To a format YYYY-MM-DD HH24:MI:SS, anyone can help to me?
You can make use of the SimpleDateFormat
Example:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
date.setTime(rec.getDateTrami().getTime());
System.out.println(format.format(date));
Documentation:
SimpleDateFormat,
DateFormat
Use java.time
Best if you can change getDateTrami() to return an OffsetDateTime or ZonedDateTime from java.time. java.time is the modern Java date and time API. It is also known as JSR-310. The code is the same no matter which of the two mentioned types is returned:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(rec.getDateTrami().format(formatter));
This prints a date and time like
2017-12-14 16:52:20
java.time is generally so much nicer to work with than the outmoded Date class and its friends.
If you cannot change the return type
I assume getDateTrami() returns a java.util.Date. Since the Date class is long outmoded, the first thing to do is to convert it to java.time.Instant. From there you perform your further operations:
Date oldfashionedDateObject = rec.getDateTrami();
ZonedDateTime dateTime = oldfashionedDateObject.toInstant()
.atZone(ZoneId.of("Atlantic/Cape_Verde"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(dateTime.format(formatter));
The result is similar to the above, of course. I on purpose made explicit in which time zone I want to interpret the point in time. Please substitute your own if it doesn’t happen to be Atlantic/Cape_Verde.
Formatting seconds since the epoch
int seconds = 29_382_000;
ZonedDateTime dateTime = Instant.ofEpochSecond(seconds)
.atZone(ZoneId.of("Atlantic/Cape_Verde"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
System.out.println(dateTime.format(formatter));
This snippet prints
1970-12-06 23:40:00
A date in December 1970. If this is incorrect, it is because 29 382 000 didn’t denote seconds since the epoch of January 1, 1970 at midnight in UTC, also known as the Unix epoch. This is by far the most common time to measure seconds from. If your seconds are measured from some other fixed point in time, I cannot guess which, and you have got a job to do to find out. Again decide which time zone you want to specify.
You could use SimpledateFormat.
new SimpleDateFormat("YYYY-MM-DD HH24:MI:SS").format(date)

Hours difference while considering the date

I need to extract the date field from DB and store it in a VO. How can I compare the hours difference from two dates.
For ex:
Let's say date1 = 01-SEP-17 10:00:00 and date2 = 05-SEP-17 12:00:00. I need to compare the two dates and perform some operations like:
if(hours>10){
//do something
}
if(hours<10){
//do something else
}
I'm just able to calculate the difference between the hours (date2-date1) as 2 but how to consider the date too while calculating the difference between the hours?
My present code:
Date dateA = someVO.getDate();
long date = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-YY HH:mm:ss");
Date date1 = new Date(date);
Date date2 = df.parse(dateA.toString());
long date1Hours = date1.getHours();
long date2Hours = date2.getHours();
long dateDiff = date1Hours-date2Hours;
if(dateDiff>10){
//something
}
else if(dateDiff<10){
//something else
}
Easy enough to do using the new Java-Time API added in Java 8:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-yy HH:mm:ss")
.toFormatter(Locale.US);
LocalDateTime date1 = LocalDateTime.parse("01-SEP-17 10:00:00", fmt);
LocalDateTime date2 = LocalDateTime.parse("05-SEP-17 12:00:00", fmt);
long hours = ChronoUnit.HOURS.between(date1, date2);
System.out.println(hours);
Output
98
First you need to change the pattern used in SimpleDateFormat, and also use a java.util.Locale to specify that the month name is in English (otherwise it uses the system default locale, and it's not guaranteed to always be English).
Then you get the correspondent millis value of each Date, calculate the difference between them and convert this to hours, using a java.util.concurrent.TimeUnit:
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy HH:mm:ss", Locale.ENGLISH);
Date date1 = df.parse("01-SEP-17 10:00:00");
Date date2 = df.parse("05-SEP-17 12:00:00");
// get the difference in hours
long dateDiff = TimeUnit.MILLISECONDS.toHours(date2.getTime() - date1.getTime());
dateDiff will be 98.
If you want to compare with the current date, just use new Date().
Daylight Saving Time issues
There's one problem with this approach. Although it doesn't make a difference for most part of the year, there can be differences due to Daylight Saving Time changes.
By default, SimpleDateFormat uses the JVM default timezone. If between the 2 dates there's a Daylight Saving Time changeover (or just an offset change), the result might be different.
Example: in Africa/Windhoek timezone, in September 3rd 2017, at 2 AM, clocks shifted 1 hour forward, from 2 AM to 3 AM (and the offset changed from +01:00 to +02:00). This means that, at that day, all local times between 2 AM and 2:59 AM don't exist in this timezone (it's like they "skipped" this hour).
So, if the JVM default timezone is Africa/Windhoek, then the difference using the code above will be 97 hours (and not 98).
Even if your JVM default timezone is not Africa/Windhoek, this can still happen, depending on the timezone and the dates involved.
Not only that, but the default timezone can be changed without notice, even at runtime. It's always better to specify which timezone you're working with instead of just relying on the default.
You can't avoid DST effects (unless you use UTC), but at least you can choose which timezone you're going to use instead of relying on the system default (that can be changed without notice).
It's possible to set a timezone in the formatter, so all dates will be parsed taking this timezone into account. In the example below, I'm using Europe/London, but of course you can change to one that best suits your case:
// set Europe/London timezone in the SimpleDateFormat
df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
Now all the parsed dates will be considered to be in London timezone (but remind that DST effects will still be considered - the advantage is that you know what timezone you're using and any changes in the JVM's default won't make your code suddenly start giving different and unexpected results).
Always use IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of all timezones using TimeZone.getAvailableIDs() - then you can choose the one that best suits your case.
If you don't want to consider DST effects, you can use TimeZone.getTimeZone("UTC") - because UTC is a standard without DST changes.
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
First you need to parse the inputs (using a DateTimeFormatter) and specify in what timezone they are. As the dates also have a timezone, I'm using a ZonedDateTime, which is the best choice for this case.
Then you can easily calculate the difference in hours using a ChronoUnit. In the example below, I'm also using London timezone as an example:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// case insensitive for month name in all caps
.parseCaseInsensitive()
// date/time pattern
.appendPattern("dd-MMM-yy HH:mm:ss")
// use English locale for month name
.toFormatter(Locale.ENGLISH)
// set a timezone
.withZone(ZoneId.of("Europe/London"));
// parse the dates
ZonedDateTime z1 = ZonedDateTime.parse("01-SEP-17 10:00:00", fmt);
ZonedDateTime z2 = ZonedDateTime.parse("05-SEP-17 12:00:00", fmt);
// calculate the difference in hours
long diffHours = ChronoUnit.HOURS.between(z1, z2);
If you want to use UTC, just change the ZoneId to ZoneOffset.UTC constant. If you want to compare with the current date, just use:
// use the same ZoneId used in the formatter if you want to consider DST effects
ZonedDateTime.now(ZoneId.of("Europe/London"));
Conversions to/from Date
If you still need to work with java.util.Date, it's possible to convert from/to the new API. In Java 8 you can use native methods, and in Java <=7 the ThreeTen Backport has the org.threeten.bp.DateTimeUtils class.
To convert a Date to the new classes:
Date date = // java.util.Date
// convert to zoneddatetime (java 8)
ZonedDateTime z = date.toInstant().atZone(ZoneId.of("Europe/London"));
// convert to zoneddatetime (java 7 ThreeTen Backport)
ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneId.of("Europe/London"));
To convert a ZonedDateTime back to a date:
// convert to zoneddatetime (java 8)
Date date = Date.from(z.toInstant());
// convert to zoneddatetime (java 7 ThreeTen Backport)
Date date = DateTimeUtils.toDate(z.toInstant());
You've essentially already got the times in milliseconds. You could always just compare the milliseconds directly instead.
long tenHoursInMillis = 36000000;
long dateVOMillis = someVO.getDate().getTime();
long dateSysMillis = System.currentTimeMillis();
if(dateSysMillis - dateAMillis > tenHoursInMillis) {
// do something
}
else if(dateSysMillis - dateAMillis < tenHoursInMillis) {
// do something else
}
// do something when they're equal

Java - SimpleDateFormat formatter to return epoch time with milliseconds [duplicate]

This question already has answers here:
Convert a date format in epoch
(6 answers)
Closed 5 years ago.
I am very new to Java and coding in general - I have some code which returns a timestamp in the following format yyyy.MM.dd HH:mm:ss:ms which is shown below:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:sss");
This returns:
2017.07.19 11:42:30:423
Is there a way to edit the "SimpleDateFormat formatter" code above to return the date/time as an epoch timestamp that includes milliseconds so that the value returned is formatted as per the below?
1500464550423
I'm hoping that I can amend the ("yyyy.MM.dd HH:mm:ss:sss") part of the SimpleDateFormat formatter code to do this.
Any help or advice is much appreciated.
Thanks
You have a simple error in the use of case in your format pattern string (these are case sensitive). And worse, you are using the old and troublesome SimpleDateFormat class. One of the many problems with it is it’s not telling you what the problem is.
So I recommend you use the modern Java date and time API instead (I am deliberately using your format pattern string verbatim):
String receivedTimetamp = "2017.07.19 11:42:30:423";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:sss");
LocalDateTime dateTime = LocalDateTime.parse(receivedTimetamp, parseFormatter);
System.out.println(dateTime);
This code throws an IllegalArgumentException: Too many pattern letters: s. I hope this calls your awareness to the fact that you are using two s’s for seconds and three s’s for fraction of second. If it still isn’t clear, the documentation will tell you that lowercase s is correct for seconds, while you need uppercase S for the fraction. Let’s repair:
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:SSS");
Now the code prints 2017-07-19T11:42:30.423, so we have managed to parse the string correctly.
To convert to milliseconds we are still missing a crucial piece of information: in what time zone should the timestamp be interpreted? I think the two obvious guesses are UTC and your local time zone (which I don’t know). Try UTC:
System.out.println(dateTime.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli());
This produces 1500464550423, which is the number you asked for. I suppose we’re done.
If you wanted your JVM’s time zone setting instead, use .atZone(ZoneId.systemDefault()) instead of .atOffset(ZoneOffset.UTC), but beware that the setting may be altered by other software running in the same JVM, so this is fragile.
First of all, check the documentation of SimpleDateFormat. The pattern that corresponds to milliseconds is an uppercase S, while the lowercase s corresponds to seconds. The problem is that SimpleDateFormat usually doesn't complain and try to parse 423 as seconds, adding this amount to your end date (giving an incorrect result).
Anyway, SimpleDateFormat just parses a String to a java.util.Date or formats the Date to a String. If you want the epoch millis value, you must get it from the Date object:
// input string
String s = "2017.07.19 11:42:30:423";
// use correct format ('S' for milliseconds)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:SSS");
// parse to a date
Date date = formatter.parse(s);
// get epoch millis
long millis = date.getTime();
System.out.println(millis); // 1500475350423
The problem is that SimpleDateFormat uses the system's default timezone, so the final value above (1500475350423) will be equivalent to the specificed date and time in my system's timezone (which can be different from yours - just for the record, my system's default timezone is America/Sao_Paulo). If you want to specify in what timezone this date is, you need to set in the formatter (before calling parse):
// set a timezone to the formatter (using UTC as example)
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
With this, the result for millis will be 1500464550423 (the equivalent to the specificed date and time in UTC).
To do the opposite (create a date from the millis value), you must create a Date object and then pass it to the formatter (also taking care of setting a timezone to the formatter):
// create date from millis
Date date = new Date(1500464550423L);
// use correct format ('S' for milliseconds)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// format date
String formatted = formatter.format(date);
Java new date/time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
As the input String has no timezone information (only date and time), first I parsed it to a LocalDateTime (a class that represents a date and time without timezone). Then I convert this date/time to a specific timezone and get the millis value from it:
// input string
String s = "2017.07.19 11:42:30:423";
// use correct format ('S' for milliseconds)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:SSS");
// as the input string has no timezone information, parse it to a LocalDateTime
LocalDateTime dt = LocalDateTime.parse(s, formatter);
// convert the LocalDateTime to a timezone
ZonedDateTime zdt = dt.atZone(ZoneId.of("Europe/London"));
// get the millis value
long millis = zdt.toInstant().toEpochMilli(); // 1500460950423
The value is now 1500460950423, equivalent to the specified date and time in London timezone.
Note that the API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
You can also use ZoneOffset.UTC constant if you want to use UTC.
To do the opposite, you can get the millis value to create an Instant, convert it to a timezone and pass it to the formatter:
// create Instant from millis value
Instant instant = Instant.ofEpochMilli(1500460950423L);
// use correct format ('S' for milliseconds)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:SSS");
// convert to timezone
ZonedDateTime z = instant.atZone(ZoneId.of("Europe/London"));
// format
String formatted = z.format(formatter);
First advice is to move to java8 java.time API instead of learning the broken java.date API
then do:
Instant i = Instant.now();
System.out.println(i.toEpochMilli());
in your case you can do:
LocalDateTime myldt = LocalDateTime.parse("2017-06-14 14:29:04",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(myldt.toInstant(ZoneOffset.UTC).toEpochMilli());
note that as soon as you play more with the api you will find more ways to achieve the same thing, at the end you will end invoking toEpochMilli
String strDate = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454
You can try
long time = System.currentTimeMillis();
If you have a java.util.Date then invoking getTime() will return the number of millis since the epoch. For example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:sss");
Date dateToBeFormatted = new Date();
// this will print a datetime literal on the above format
System.out.println(formatter.format(dateToBeFormatted));
// this will print the number of millis since the Java epoch
System.out.println(dateToBeFormatted.getTime());
The key point here is that in order to get the number of millis since the epoch you do not need a SimpleDateFormatter because the number of millis since the epoch is a property of the Date.

Displaying wrong time difference

I tried many ways to display the difference between two times, but I am unable to find a solution:
long strt = System.currentTimeMillis();//1462968291733
Thread.sleep(5000);
long end = System.currentTimeMillis();//1462968296733
long diff = end - strt;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(diff);
TimeZone timeZone = TimeZone.getTimeZone("IST");
calendar.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
System.out.println(calendar.getTime());//05:30:05
It is printing wrong output:
Thu Jan 01 05:30:05 IST 1970
The output should be
Thu Jan 01 00:00:05 IST 1970
You are getting confuse with the time zone. Try the following:
long strt = System.currentTimeMillis();// 1462968291733
Thread.sleep(5000);
long end = System.currentTimeMillis();// 1462968296733
long diff = end - strt;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(diff);
TimeZone cutsomTimeZone = TimeZone.getTimeZone("IST");
DateFormat formatter = new SimpleDateFormat
("EEE MMM dd HH:mm:ss zzz yyyy");
formatter.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
System.out.println(formatter.format(calendar.getTime()));//
formatter.setTimeZone(cutsomTimeZone);
System.out.println(formatter.format(calendar.getTime()));
First, as the javadoc says, System.currentMillis() return the number of milliseconds since 1 January 1970 in UTC which is obviously different from IST.
Second, the Date object return by calendar.getTime() does not bear a timezone. The output you get with System.out.println(calendar.getTime()) use the default TimeZone of your system which seems to be IST.
Third, please don't use the Date api, it is really bad. When possible, prefer the java.time one.
This is because the default print out uses the default locale, which is +5:30 in your case.
You'll need to format the output in the time zone you want, e.g. by using SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(calendar.getTime()));
The answer by dejvuth and the answer by orris are both correct.
Avoid the old date-time classes. They have been supplanted in Java 8 and later by the java.time framework. For Java 6 & 7, much of the functionality has been back-ported by the ThreeTen-Backport project, and further adapted to Android by the ThreeTenABP project.
No need for time zones at all to capture elapsed time.
An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds. In Java 8 the current moment is captured up to a resolution of only milliseconds, but a new implementation of Clock in Java 9 will capture up to nanoseconds depending on your computer’s clock hardware capability.
Instant start = Instant.now();
…
Instant stop = Instant.now();
A Duration captures a span of time as a total number of whole seconds and a fraction of a second as nanoseconds. This value is not attached to the timeline.
Duration duration = Duration.between( start , stop );
The java.time classes use the ISO 8601 standard when generating a textual representation of a date-time value. For a duration of two and a half seconds, you will get a value like PT2.5S where the P marks the beginning (for Period), and the T separates any years-month-days from hours-minutes-seconds. This format prevents the ambiguity of the clock-format where 00:00:02.5 looks like a time-of-day of two minutes past midnight. But if you so desire you can interrogate the Duration for the numbers.
String output = duration.toString();

Getting yesterday - The method getDate() from the type Date is deprecated

I try to get the date of yesterday. So I write the next function:
public String getYestrday() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date.getDate() - 1);
}
But it gives me the next warning:
The method getDate() from the type Date is deprecated
and it doesn't do it work.
Thank you for your help.
Date#getDate() is a deprecated method after JDK 1.1. You should be using Calendar class instead to manipulate dates.
From API:
Prior to JDK 1.1, the class Date had two additional functions. It
allowed the interpretation of dates as year, month, day, hour, minute,
and second values. It also allowed the formatting and parsing of date
strings. Unfortunately, the API for these functions was not amenable
to internationalization. As of JDK 1.1, the Calendar class should be
used to convert between dates and time fields and the DateFormat class
should be used to format and parse date strings. The corresponding
methods in Date are deprecated.
It is also clearly documented in the API using Date#getDate() to use Calendar#get(Calendar.DATE);
Deprecated. As of JDK version 1.1, replaced by
Calendar.get(Calendar.DAY_OF_MONTH)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
Use java.util.Calendar to do it. Or try JODA.
you can use Calendar class to do the same task:
Calendar c = new Calendar();
//c.add(Calendar.DAY_OF_MONTH, -1);
Date d = c.getTime();
Avoid java.util.Date & .Calendar
The accepted answer is correct. However, the java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package (in Java 8).
Separate Date-Time Manipulation From Formatting
Also, the code in the question mixes date-time work with formatting. Separate those tasks to make your code clear and testing/debugging easier.
Time Zone
Time zone is critical in date-time work. If you ignore the issue, the JVM's default time zone will be applied. A better practice is to always specify rather than rely on default. Even when you want the default, explicitly call getDefault.
The beginning of the day is defined by the time zone. A new day dawns earlier in Paris than in Montréal. So if by "yesterday" you mean the first moment of that day, then you should (a) specify a time zone, and (b) call withTimeAtStartOfDay.
Joda-Time
Example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime today = DateTime.now( timeZone );
Or convert from a java.util.Date object.
DateTime today = new DateTime( myJUDate, timeZone );
Subtract a day to get to yesterday (or day before).
DateTime yesterday = today.minusDays( 1 );
DateTime yesterdayStartOfDay = today.minusDays( 1 ).withTimeAtStartOfDay();
By default, Joda-Time and java.time parse/generate strings in ISO 8601 format.
String output = yesterdayStartOfDay.toString(); // Uses ISO 8601 format by default.
Use a formatter for a full date as four digit year, two digit month of year, and two digit day of month (yyyy-MM-dd). Such a formatter is already defined in Joda-Time.
String outputDatePortion = ISODateFormat.date().print( yesterdayStartOfDay );
Following works for me
int date = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

Categories

Resources