Add 30 seconds to time in yyyyMMddHHmmss format in java [duplicate] - java

This question already has answers here:
How do I say 5 seconds from now in Java?
(11 answers)
Closed 4 years ago.
How to add 30 seconds to the datetime in the format yyyyMMddHHmmss in java
SO far I have done this
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date d;
d = df.parse(requestDate);
System.out.println(" date d "+d);
Long time = d.getTime();
time +=30;
Date d2 = new Date(time);
System.out.println(" date d2 "+d2);
And the output I am getting is not correct and both are same time . The output I am getting is
date d Wed Apr 30 19:32:47 IST 2014
date d2 Wed Apr 30 19:32:47 IST 2014

tl;dr
LocalDateTime.parse(
"20180123123456" ,
DateTimeFormatter.ofPattern( “uuuuMMddHHmmss” )
).plusSeconds( 5 )
java.time
Use modern java.time classes rather than terrible old legacy classes.
Parse as a LocalDateTime as your input apparently lacks any indicator of offset or time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuuMMddHHmmss” ) ;
LocalDateTime ldt = LocalDateTime.parse( “20180123123456” , f ) ;
Duration d = Duration.ofSeconds( 30 ) ; // Represent a span of time unattached to the timeline.
LocalDateTime later = ldt.plus( d ) ;
String output = later.format( f ) ; // Generate a String representing the value of this object.
Tip: Use ISO 8601 standard formats instead.
Search Stack Overflow for more info. This has been covered many times already.
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.

You have the correct idea, but made a small mistake. getTime gives the time in milliseconds, not seconds. So you need to add 30000.

You need add 30000 millisecond(30 sec)where 1000 Millisecond means 1 Second
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date d;
d = df.parse(requestDate);
System.out.println(" date d "+d);
Long time = d.getTime();
time +=30000;//Here Change
Date d2 = new Date(time);
System.out.println(" date d2 "+d2);

Please read the Date.getTime() doc: Returns the number of milliseconds...
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date d;
d = df.parse(requestDate);
System.out.println(" date d "+d);
Long time = d.getTime();
time +=30000; //<---milliseconds
Date d2 = new Date(time);
System.out.println(" date d2 "+d2);

Related

Android - Convert GMT time to Locale time

I am trying to convert UTC time to user's Locale time. However, I am getting back the same UTC time.
Apparently, setting the time zone to locale/default does not work.
Another method seems to be available using Instant, but requires API level 26.
This is my input date in string: "2020-01-16T19:44:48.303+0000".
I am expecting to have the date and time in this format: "M/dd/yy - h:mm aa"
private String toLocaleTime(String timeStr){
// Date date;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+0000'");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String localeTime = "";
try {
//date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US).parse(timeStr);
localeTime = simpleDateFormat.format(simpleDateFormat.parse(timeStr));
} catch (ParseException e) {
e.printStackTrace();
}
//String str = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US).format(date);
Log.d("LocaleTime", ""+ localeTime);
return localeTime;
}
java.time
A Locale has nothing to do with the content of a date-time object. A locale only comes into the picture when generating text to represent the value of the date-time object. I suspect your intention is to adjust from an offset-from-UTC of hours-minutes-seconds to the wall-clock time used by the people of a particular region (a time zone).
Never use SimoleDateFormat or Date or Calendar. These terrible date-time classes were supplanted by java.time years ago. For Android before 26, add the ThreeTenABP library to your project.
This is my input date in string: "2020-01-16T19:44:48.303+0000"
Tip: The java.time classes and other date-time frameworks work better if you include the colon character between the hours and seconds in the offset: +00:00.
If all your inputs have the same offset, replace that part of the string.
String input = "2020-01-16T19:44:48.303+0000".replace( "+0000" , "+00:00" ) ;
Parse as an Instant, a moment in UTC.
Instant instant = Instant.parse( input ) ;
Generate a string in your desired format. Do you really want one-digit month with two digit day? And one digit hour with two digit minute?
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/dd/uu - h:mm a" ).withLocale( locale ) ;
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
String output = instant.atZone( z ).format( z ) ;
I suggest you instead let java.time automatically localize for you with DateTimeFormatter.ofLocalizedDateTime.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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, Java SE 10, Java SE 11, and later - 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
Most 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….
You tell the parsing date formatter to parse using UTC time zone, the tell the formatting date formatter to format using the default time zone (by not telling it anything):
String input = "2020-01-16T19:44:48.303+0000";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+0000'");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = inputFormat.parse(input);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
// Not needed: outputFormat.setTimeZone(TimeZone.getDefault());
String output = outputFormat.format(date);
System.out.println("input: " + input);
System.out.println("output: " + output);
System.out.println(new SimpleDateFormat("zzzz XX").format(date));
Output
input: 2020-01-16T19:44:48.303+0000
output: 2020-01-16T14:44:48.303
Eastern Standard Time -0500

How to convert a string to date with UTC/GMT timezone

I have an android app that receives a string in this format:"MM-dd-yyyy HH:mm:ss" from my server. I want to convert this string to a Date object with UTC as timezone since the time in the string is UTC. I've already checked several similar questions but didn't find my answer
Here is what I'm using currently:
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
Date date = new Date();
try {
date = format.parse(itemContent [3]);
entity.setValidTill(date);
}catch (Exception e){
}
But what it does when I print that date with Log is show it as:
Sun Aug 27 15:00:00 GMT+04:00 2017
I want it to be:
Sun Aug 27 15:00:00 GMT 00:00 2017
So here is the main question how to get DateTime for UTC using a string with format as above?
Edit:
Just put it in a better context. I'm trying to get users to see the difference between current datetime & the that datetime saved in server. So my solution was to get gmt time for users & compare with the server time(which is gmt) so everyone see same difference regardless of their timezone. With C# you can get DateTime.UtcNow while with java I couldn't find an alternative
Briefly, as your Question is really a duplicate of many others…
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Parse your input string as a LocalDateTime as it lacks any indicator of offset-from-UTC or time zone.
Define a formatter to parse your input string.
String input = "08-27-2017 15:00:00" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2017-08-27T15:00
A LocalDateTime is not a moment on the timeline, only a rough idea about a range of possible moments. Has no meaning without the context of an offset (or time zone).
If you are certain that input was intended for UTC, assign the constant ZoneOffset.UTC for a OffsetDateTime.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
odt.toString(): 2017-08-27T15:00Z
To calculate a delta between that moment and the current moment, use the Period class for coarser granularity in your span of time, or Duration for finer granularity. Both classes generate strings in standard ISO 8601 format of PnYnMnDTnHnMnS.
OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC ) ;
Duration d = Duration.between( odt , now ) ;
now.toString(): 2017-08-27T21:16:56.396Z
d.toString(): PT6H16M56.396S
See this code run live at IdeOne.com.
In the standard strings seen above, the Z is short for Zulu and means UTC.
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, Java SE 10, 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….
just add this code under the first line of your code:
format.setTimeZone(TimeZone.getTimeZone("UTC"));

getTimeInMillis() in java [duplicate]

I have a problem in converting the date in java, don't know where i am going wrong...
String dateStr = "2011-12-15";
String fromFormat = "yyyy-mm-dd";
String toFormat = "dd MMMM yyyy";
try {
DateFormat fromFormatter = new SimpleDateFormat(fromFormat);
Date date = (Date) fromFormatter.parse(dateStr);
DateFormat toformatter = new SimpleDateFormat(toFormat);
String result = toformatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
Input date is 2011-12-15 and I am expecting the result as "15 December 2011", but I get it as "15 January 2011"
where am I going wrong?
Your fromFormat uses minutes where it should use months.
String fromFormat = "yyyy-MM-dd";
I think the fromFormat should be "yyyy-MM-dd".
Here is the format:
m == Minute in Hour
M == Month in Year
More: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
From format should be:
String fromFormat = "yyyy-MM-dd"
Look at the javadoc of SimpleDateFormat and look at what the m represents. Not months as you think but minutes.
String fromFormat = "yyyy-MM-dd";
m in SimpleDateFormat stands for minutes, while M stands for month. Thus your first format should be yyyy-MM-dd.
tl;dr
LocalDate.parse( "2011-12-15" ) // Date-only, without time-of-day, without time zone.
.format( // Generate `String` representing value of this `LocalDate`.
DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG ) // How long or abbreviated?
.withLocale( // Locale used in localizing the string being generated.
new Locale( "en" , "IN" ) // English language, India cultural norms.
) // Returns a `DateTimeFormatter` object.
) // Returns a `String` object.
15 December 2011
java.time
While the accepted Answer is correct (uppercase MM for month), there is now a better approach. The troublesome old date-time classes are now legacy, supplanted by the java.time classes.
Your input string is in standard ISO 8601 format. So no need to specify a formatting pattern for parsing.
LocalDate ld = LocalDate.parse( "2011-12-15" ); // Parses standard ISO 8601 format by default.
Locale l = new Locale( "en" , "IN" ) ; // English in India.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG )
.withLocale( l );
String output = ld.format( f );
Dump to console.
System.out.println( "ld.toString(): " + ld );
System.out.println( "output: " + output );
ld.toString(): 2011-12-15
output: 15 December 2011
See live code in IdeOne.com.
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, Java SE 10, 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.
Well this may not be your case but may help someone. In my case after conversion, day of month and month set 1. So whatever date is, after conversion i get 1 jan which is wrong.
After struggling i found that in date format i have used YYYY instead of yyyy. When i changed all caps Y to y it works fine.

store current date and date 1 year from current in java

I have everything setup already to store the current date to a variable in Java. What I am trying to figure out is how to store a date of 1 year after the current date.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Scanner;
import java.util.Calendar;
Here is what I have for the current date:
DateFormat newDate = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
startDate = newDate.format(date);
So if it were today for example it would store 2/18/2013. I am trying to store the date 2/18/2014. How would I go about doing this?
If you do not want to drag external libraries, just use calendar.add(Calendar.YEAR, 1)
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 1); // to get previous year add -1
Date nextYear = cal.getTime();
Note, if the date was 29/Feb/2012 and you added 1 year, you will get 28/Feb/2013
tl;dr
LocalDate.parse(
"2/18/2013" ,
DateTimeFormatter.ofPattern ( "M/d/uuuu" )
).plusYears( 1 )
Details
The accepted Answer is correct, but outdated as of Java 8.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. 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.
LocalDate
These new classes include LocalDate, to represent a date-only value with no time-of-day nor time zone.
First we must parse the String input. The java.time formatter uses pattern codes similar to the old classes, but not exactly the same. So be sure to read the new doc carefully.
Padded Zero
Notice that your input String lacks leading zero digit for some values. That means you should use single pattern codes, M and d rather than MM and dd. Double codes means you expect padding zero to always be included for otherwise single-digit values, 02 rather than 2.
String input = "2/18/2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M/d/uuuu" );
LocalDate localDate = LocalDate.parse ( input , formatter );
Add a year. The java.time framework takes care of leap year.
LocalDate yearLater = localDate.plusYears ( 1 );
Dump to console.
System.out.println ( "localDate: " + localDate + " and yearLater: " + yearLater );
localDate: 2013-02-18 and yearLater: 2014-02-18
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, Java SE 10, Java SE 11, and later - 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
Most 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.
Use Calendar#add(int field, int amount) method.You should use Calendar API in-order to manipulate date and time operations.
Calendar today = Calendar.getInstance();
Calendar nextYearToday = today;
nextYearToday.add(Calendar.YEAR, 1);
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 1); // to get previous year add 1
cal.add(Calendar.DAY_OF_MONTH, -1); // to get previous day add -1
Date expiryDate = cal.getTime();
System.out.println("today is --> "+today);
System.out.println("expiryDate is --> "+expiryDate);
OutPut
today is --> Fri Dec 01 10:10:52 GMT+05:30 2017
expiryDate is --> Fri Nov 30 10:10:52 GMT+05:30 2018
date today is -> Fri Dec 01 10:10:52 GMT+05:30 2017
expiryDate is -> Fri Nov 30 10:10:52 GMT+05:30 2018
In Android is simpler than ever:
oneYearAfterDate = new Date(date.getTime() + DateUtils.YEAR_IN_MILLIS )

How to set an expiration date in java

I am trying to write some code to correctly set an expiration date given a certain date.
For instance this is what i have.
Date lastSignupDate = m.getLastSignupDate();
long expirationDate = 0;
long milliseconds_in_half_year = 15778463000L;
expirationDate = lastSignupDate.getTime() + milliseconds_in_half_year;
Date newDate = new Date(expirationDate);
However, say if i the sign up date is on 5/7/2011 the expiration date output i get is on 11/6/2011 which is not exactly half of a year from the given date. Is there an easier way to do this?
I would use the Calendar class - the add method will do this kind of thing perfectly.
http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 6);
java.util.Date expirationDate = cal.getTime();
System.err.println(expirationDate);
Here's a simple suggestion using joda-time:
DateTime dt = new DateTime(lastSignupDate);
dt = dt.plusDays(DateTimeConstants.MILLIS_PER_DAY * 365 / 2);
// you can also use dt.plusDays(364 / 2);
You can also use a Calendar:
Calendar c = Calendar.getInstance();
c.setTime(lastSignupDate);
c.add(Calendar.MILLISECOND, MILLIS_PER_DAY * 365 / 2);
// or c.add(Calendar.DAY_OF_YEAR, 364 / 2);
tl;dr
java.time.LocalDate.of( 2011 , Month.MAY , 7 )
.plusMonths( 6 )
.toString()
2011-11-07
java.time
You are using date-time values, so you must account for issues such as time zones, anomalies, and leap year. But you only want a date without a time-of-day and without a time zone, so much easier if you use a date-only class rather than a date-with-time class.
The modern approach uses java.time rather than the troublesome legacy date-time classes.
if i the sign up date is on 5/7/2011 the expiration date output i get is on 11/6/2011 which is not exactly half of a year from the given date
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2011 , Month.MAY , 7 ) ;
You can do math with the java.time classes. Look for plus… and minus… methods.
LocalDate sixMonthsLater = ld.plusMonths( 6 ) ;
Or pass the amount of time.
Period p = Period.ofMonths( 6 ) ;
LocalDate sixMonthsLater = ld.plus( p ) ;
See this code run live at IdeOne.com.
2011-05-07
2011-11-07
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
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.
Do you really need an expiration-date, which is accurate to the millisecond?
I would implement it as 6 Months from x.
Jan. 1 => Jul 1
Sep. 28=> Feb 28
Sep. 29=> Feb 28
Sep. 30=> Feb 28
Oct. 1=> Mar 1
Maybe you like to be generous, and say 'Mar 1' for 'Sep 29 and 30' too.
Here's an example of using Date with TimeUnit that's a little more readable:
long year = TimeUnit.MILLISECONDS.convert(365, TimeUnit.DAYS);
Date expiry = new Date(System.currentTimeMillis() + year);
System.out.println(expiry);
Shame it doesn't have year and day, look at GregorianCalendar or Jodatime for a better API.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new Date().getTime());
// 10 minutes expiration time
calendar.add(calendar.MINUTE, 10);
// prints 10 minutes ahead time
System.out.println(new Date(calendar.getTime().getTime()));

Categories