SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Now if I want to add 2 more hours to time1, like:
7:30 + 2 = 9:30
how do I add the 2 hours?
java.util.Date is deprecated, you should use java.util.Calendar instead.
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date myDate = parser.parse("7:30");
Calendar cal =Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.HOUR_OF_DAY,2); // this will add two hours
myDate = cal.getTime();
And even better solution is to use Joda Time - Java date and time API.
From their website - Joda-Time provides a quality replacement for the Java date and time classes.
Convert java.util.Date into java.util.Calendar Object and use Calendar.add() method to add Hours
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Calendar cal =Calendar.getInstance();
cal.setTime(time1);
cal.add(Calendar.Hour_Of_Day, 2);
time1 =cal.getTime();
System.out.println(parser.format(time1));//returns 09:30
tl;dr
LocalTime.parse( "07:30" ).plusHours( 2 )
…or…
ZonedDateTime.now( ZoneId.of( " Pacific/Auckland" ) )
.plusHours( 2 )
java.time
The old date-time classes such as java.util.Date, .Calendar, and java.text.SimpleDateFormat should be avoided, now supplanted by the java.time classes.
LocalTime
For a time-of-day only value, use the LocalTime class.
LocalTime lt = LocalTime.parse( "07:30" );
LocalTime ltLater = lt.plusHours( 2 );
String output = ltLater.toString(); // 09:30
Instant
For a given java.util.Date, convert to java.time using new methods added to the old classes. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myUtilDate.toInstant();
Or capture current moment in UTC as an Instant.
Instant instant = Instant.now();
Add two hours as seconds. The TimeUnit class can convert hours to seconds.
long seconds = TimeUnit.HOURS.toSeconds( 2 );
Instant instantLater = instant.plusSeconds( seconds );
ZonedDateTime
To view in the wall-clock time of some community, apply a time zone. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You can add hours. The ZonedDateTime class handles anomalies such as Daylight Saving Time.
ZonedDateTime zdtLater = zdt.plusHours( 2 );
Duration
You can represent that two hours as an object.
Duration d = Duration.ofHours( 2 ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;
Related
I'm trying to make a code that tells me how many days left for me to go college, but I am not able to do it with the current date. I can easily make it by setting a date, but I want the current date, so I have to use the calendar method, but can't do math using it.
My code:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
System.out.println(start - calendar.getTime());
tl;dr
ChronoUnit.DAYS.between(
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) ,
LocalDate.parse( "10/06/2022" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
)
Details
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date/Calendar.
Also, you are attempting to use a date-time class representing a date with time-of-day as seen in UTC (offset of zero) to hold a date-only value. Square peg, round hole.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate graduationDate = LocalDate.parse( "10/06/2022" , f ) ;
Determine today's date. That requires a time zone. For any given moment, the date varies around the globe by time zone.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ; // Or ZoneId.systemDefault()
LocalDate today = LocalDate.now( z ) ;
Calculate elapsed time using java.time.temporal.ChronoUnit.
long days = ChronoUnit.DAYS.between( today , graduationDate ) ;
See this code run live at IdeOne.com.
graduationDate: 2022-06-10
today: 2022-03-05
days: 97
Tip: Learn about the ISO 8601 standard for exchanging date-time values as text.
Calendar calendar = Calendar.getInstance();
Calendar collegeDate = Calendar.getInstance();
collegeDate.set(Calendar.DATE,10);
collegeDate.set(Calendar.MONTH, 5);
collegeDate.set(Calendar.YEAR, 2022);
System.out.println(Duration.between(calendar.toInstant(), collegeDate.toInstant()).toDays());
You can try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
long dif = Math.abs(calendar.getTimeInMillis() - start.getTime());
long result = TimeUnit.DAYS.convert(dif, TimeUnit.MILLISECONDS);
System.out.println(result);
I need to create a new Calendar object that contains the current date but the time needs to be set from a given String of format HH:mm:ss.
I create a new calendar object with current date and time and then use a SimpleDateFormat object to parse the string and set the time from that one but that only overwrites the calendar object with the parsed time and Jan 1 1970:
def currentTime = new java.util.Date();
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(currentTime);
java.util.Date inTime = new SimpleDateFormat("HH:mm:ss").parse(initialTime);
calendar1.setTime(inTime);
Is there a way to get the values of Hour, Minute, Seconds and Milliseconds from the Date object to use it with calendar.set(Calendar.HOUR_OF_DAY, hour), etc.?
tl;dr
GregorianCalendar.from( // Converting from modern java.time class to troublesome legacy class. Do so only if you must. Otherwise use only the java.time classes.
ZonedDateTime.of( // Modern java.time class representing a moment, a point on the timeline, with an assigned time zone through which to see the wall-clock time used by the people of a particular region.
LocalDate.now( ZoneId.of( “Pacific/Auckland” ) ) , // The current date in a particular time zone. For any given moment, the date varies around the globe by zone.
LocalTime.of( 12 , 34 , 56 ) , // Specify your desired time-of-day.
ZoneId.of( “Pacific/Auckland” ) // Assign a time zone for which the date and time is intended.
)
)
java.time
The modern approach uses the java.time classes.
ZoneId z = ZoneId.of( “America/Montreal” ) ;
LocalDate ld = LocalDate.now( z ) ;
LocalTime lt = LocalTime.of( 12 , 34 , 56 ) ; // 12:34:56
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
You can extract the time-of-day (or date) from an existing ZonedDateTime.
LocalTime lt = zdt.toLocalTime() ;
LocalDate ld = zdt.toLocalDate() ;
Best to avoid the troublesome old legacy date-time classes added before Java 8. But if you must, you can convert between the modern and legacy classes. Call on new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ; // If you must, but better to avoid the troublesome old legacy classes.
Not sure if this helps you.
String hhmmss = "10:20:30";
String[] parts = hhmmss.split(":");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal.set(Calendar.SECOND, Integer.parseInt(parts[2]));
Calendar objet Time is a java.util.Date object with the standard format. You can not set date with a specific format to your calendar.
To get the Date details (Hours, Minutes ...) try :
final Date date = new Date(); // your date
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
final int year = cal.get(Calendar.YEAR);
final int month = cal.get(Calendar.MONTH);
final int day = cal.get(Calendar.DAY_OF_MONTH);
final int hour = cal.get(Calendar.HOUR_OF_DAY);
final int minute = cal.get(Calendar.MINUTE);
final int second = cal.get(Calendar.SECOND);
I need to replace SimpleDataFormat with Java 8 DateTimeFormatter. Below is the code with SimpleDateFormat.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(source);
Now I need to change it to DateTimeFormatter. I tried as below
LocalDateTime ld = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Date startdate = dtf.parse(dtf);
Now this is generating exception.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse("2017-02-11", dtf);
System.out.println(localDate.toString());
if you want Date object from LocalDate,the following works
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
As #JonSkeet advised, If you're using Java 8 you should probably avoid java.util.Date altogether
If looking for equivalent of your sdf in DateTimeFormatter try DateTimeFormatter.ISO_LOCAL_DATEExplore the DateTimeFormatter class for more formats.
LocalDateTime time = LocalDateTime.now();
time.format(DateTimeFormatter.ISO_LOCAL_DATE);
Use LocalDate instead of LocalDateTime if intrested in Date only.
tl;dr
java.util.Date.from(
LocalDate.parse( "2017-01-23" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
.toInstant()
)
No need of formatting pattern
No formatting pattern needed. Your input string happens to be in standard ISO 8601 format. These standard formats are used by default in the java.time classes for parsing and generating strings.
LocalDate
Use LocalDate for a date-only value, without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2017-01-23" );
ZonedDateTime
If you want a date-time, let java.time determine the first moment of the day. Do not assume that first moment is 00:00:00.
Determining first moment of the day requires a time zone. The date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ld.atStartOfDay( z );
If you want to perceive that moment through the lens of UTC, extract an Instant object.
Instant instant = zdt.toInstant();
The Instant is equivalent to the old legacy class java.util.Date. Both represent a moment on the timeline in UTC. The modern class has a finer resolution, nanoseconds rather than milliseconds.
Avoid java.util.Date
As others mentioned, you should stick with the modern java.time classes. But if you must, you can convert. Look to new methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;
One way of doing it would be -
LocalDateTime ld = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String date = ld.format(dtf);
I'm trying to convert the created_utc date from Reddit's json to a Date object, but I keep getting an "Unparceable" error. An example of their dates is: created_utc": 1.43701862E9, which I'm told is a unix timestamp.
From my research this code should convert it:
String date = "1.43701862E9";
java.util.Date time = new java.util.Date((long)date*1000);
but obviously I'm getting an error on multiplying the date by 1000.
This is the code I normally use to convert string dates:
String date = "1.43701862E9";
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
format.parse(date);
This should work for you:
public static void main(String[] args) {
String date = "1.43701862E9";
java.util.Date time = new java.util.Date(Double.valueOf(date).longValue()*1000);
System.out.println(time);
}
Output:
Wed Jul 15 23:50:20 EDT 2015
Since you're using scientific notation you can't parse the String using the Long class: Long.parseLong(String s) (Nor can you simply cast a String, as you're trying). Instead, I used the Double.valueOf() method and preserve the Long using .longValue()
The answer by Trobbins is correct but old-school. I lifted that Answer’s math, and used the new java.time classes.
java.time
In Java 8 and later, you can use the new java.time package which supplants the troublesome old java.util.Date/.Calendar classes. (Tutorial)
String input = "1.43701862E9";
long milliSinceEpoch = Double.valueOf( input ).longValue() * 1_000L ;
Instant instant = Instant.ofEpochMilli( milliSinceEpoch ) ;
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ) ;
Try to avoid java.util.Date/.Calendar, but if need be you can convert.
java.util.Date date = Date.from( zdt.toInstant() ); // Or… Date.from( instant );
java.util.Calendar calendar = GregorianCalendar.from( zdt );
I must convert a linux timestamp to android date.
i get this number from server
1386889262
I have written a small code snippet.
Date d = new Date(jsonProductData.getLong(MTIME));
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy");
.setTimeZone(TimeZone.getTimeZone("GMT"));
formatTime = f.format(d);
but it doesen't convert right, this is my result
17.01.1970
EDIT:
Normally i must get this here
12.12.2013
Is there an another method to get the right date???
if your UNIX time stamp is of 10 digit then it does not include milliseconds so do this first 1386889262*1000
and if its 13 digit then it includes milliseconds also then you do not have to multiply unix timestamp with 1000.
In Kotlin we can use this function:
val unix=1386889262*1000 /*if time stamp is of 10 digit*/
val dateFormat = SimpleDateFormat("dd-MM-yy HH:mm:ss");
val dt = Date(unix);
textview.settext(dateFormat.format(dt))
UNIX timestamp should be in milliseconds so multiply the Long value by 1000. So your value 1386889262 would be 1386889262000:
tl;dr
Instant.ofEpochSecond( 1386889262L )
.atZone( ZoneId.of( "Pacific/Auckland" ) )
.toLocalDate()
.toString()
java.time
You appear to have a count of whole seconds from the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
The modern approach uses the java.time classes that supplant the troublesome old date-time classes bundled with the earliest versions of Java. For older Android see the ThreeTen-Backport and ThreeTenABP projects.
An Instant represents a point on the timeline in UTC with a resolution of nanoseconds (up to nine digits of decimal fraction).
Instant instant = Instant.ofEpochSecond( 1386889262L ) ;
To generate a String representing this moment, call toString.
String output = instant.toString() ;
Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. Assign a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract a date-only value for your purposes.
LocalDate ld = zdt.toLocalDate() ;
Generate a String.
String output = ld.toString() ;
For other formats in your String, search Stack Overflow for DateTimeFormatter.
Your timestamp or epoch time seems in sec "1386889262". You have to do something like this:
long date1 = 1386889262*1000;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
Date dt = new Date(date1);
datedisplay.setText(dateFormat.format(dt));
You can also get timestamp in java via
new Date().getTime() ;
It returns a long value.