I have seconds since 1970 january 1 UTC (Epoch time).
1320105600
I need to convert that seconds into date and time in below format.
Friday,November 4,2011 5:00,AM
How can I achieve this?
In case you're restricted to legacy java.util.Date and java.util.Calendar APIs, you need to take into account that the timestamps are interpreted in milliseconds, not seconds. So you first need to multiply it by 1000 to get the timestamp in milliseconds.
long seconds = 1320105600;
long millis = seconds * 1000;
This way you can feed it to a.o. the constructor of java.util.Date and finally use SimpleDateFormat to convert a java.util.Date to java.lang.String in the desired date format pattern, if necessary with a predefined time zone (otherwise it would use the system default time zone, which is not GMT/UTC per se and thus the formatted time might be off).
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // Tuesday,November 1,2011 12:00,AM
In case you're already on Java8, there's a LocalDateTime#ofEpochSecond() which allows you to feed epoch seconds directly without the need for multiplying into milliseconds flavor.
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
System.out.println(formattedDate); // Tuesday,November 1,2011 12:00,AM
long yourSeconds = 1320105600L;
Date date = new Date(yourSeconds * 1000);
See this javadoc for more info. The constructor needs milliseconds.
To display this date in an appropriate format you should check DateFormat
Here is an example:
DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
System.out.println(df.format(date));
java.time
The Answer by BalusC is good in that it points you to using java.time. But that Answer uses LocalDateTime where Instant is more appropriate. A LocalDateTime is not a moment on the timeline as it purposely has no concept of offset-from-UTC or time zone.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
A moment on the timeline in UTC with a resolution up to nanoseconds is represented by the Instant class.
Instant instant = Instant.ofEpochSecond ( 1_320_105_600L );
Dump to console. Your input value is the first moment of November 1, 2011 in UTC. The Z on the end, short for 'Zulu', means UTC.
System.out.println ( "instant: " + instant );
instant: 2011-11-01T00:00:00Z
ZonedDateTime
In your comments you mention wanting to see this date-time through the lens of the America/Chicago time zone. Use a proper time zone name. Apply a time zone, ZoneId, to get a ZonedDateTime object. We see that Chicago is five hours behind UTC on that date.
ZoneId zoneId = ZoneId.of ( "America/Chicago" );
ZonedDateTime zdt = instant.atZone ( zoneId );
zdt: 2011-10-31T19:00-05:00[America/Chicago]
Strings
The Strings seen above are in standard ISO 8601 format. To generate strings in other formats, use the DateTimeFormatter class. You can specify your own custom pattern. But generally best to let java.time automatically localize to the human language and cultural norms encoded in a Locale object.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL );
formatter = formatter.withLocale ( Locale.US );
String output = zdt.format ( formatter );
Monday, October 31, 2011 7:00:00 PM CDT
To specify your own custom format, search Stack Overflow for many examples and more discussion.
int seconds = 1320105600;
Date date = new Date(seconds * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a");
System.out.println(sdf.format(date));
The trick is to use java.util.Date and java.text.DateFormat to get the format you want. You can look up how to do it in tutorials on the Web.
Related
I have to get DateTime with using TimeZone and then get Timestamp from that DateTime
My Code is give below :
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = new Date();
String currentTime = formatter.format(dt);
System.out.println("currentTime>>>>" + currentTime);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Canada/Eastern"));
Date parsedDate = format.parse(currentTime);
System.out.println("parsedDate>>>>" + parsedDate);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
System.out.println("timestamp>>>>>>" + timestamp);
Problem is that I am not getting right datetime of Canada/Eastern TimeZone in timestamp.
I am getting the below time
currentTime>>>>2016-11-09 15:17:09
parsedDate>>>>Thu Nov 10 01:47:09 IST 2016
timestamp>>>>>>2016-11-10 01:47:09.0
Indian time is correct : 2016-11-09 15:17:09
When I parse it to Canada/Eastern it shows : Thu Nov 10 01:47:09 IST 2016
But eastern canada time is 04:50:21 EST Wednesday, 9 November 2016
I am using Java with Eclipse Mars 1.
tl;dr
Instant.now()
.atZone( ZoneId.of( "America/Toronto" ) )
No parsing! Do not parse to adjust time zone.
Avoid the troublesome old classes: java.text.SimpleDateFormat, java.util.Date, java.util.TimeZone.
java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
2016-11-10T04:52:02.586Z
Time zone
You can adjust this Instant into a time zone by applying a ZoneId to get a ZonedDateTime.
Do not parse as a way to adjust time zone! perhaps you are conflating a date-time object with a string that might represent its value. A date-time object can generate a string, and can parse a string, but the string is always distinct and separate from the date-time object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. 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(!).
Furthermore, your Canada/Eastern zone is actually just an alias for the real zone of America/Toronto.
ZoneId z = ZoneId.of( "America/Toronto" );
ZonedDateTime zdt = instant.atZone( z );
2016-11-09T23:52:02.586-05:00[America/Toronto]
You could adjust into India time as well.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = instant.atZone( zKolkata );
2016-11-10T10:22:02.586+05:30[Asia/Kolkata]
Dump to console.
System.out.println( "instant: " + instant );
System.out.println( "zdt: " + zdt );
System.out.println( "zdtKolkata: " + zdtKolkata );
instant: 2016-11-10T04:52:02.586Z
zdt: 2016-11-09T23:52:02.586-05:00[America/Toronto]
zdtKolkata: 2016-11-10T10:22:02.586+05:30[Asia/Kolkata]
See live code in IdeOne.com.
Database
By Timestamp I assume you meant java.sql.Timestamp. That class is now outmoded by the java.time classes, if you have a JDBC driver that complies with JDBC 4.2 or later. Just pass the Instant object to PreparedStatement::setObject. Fetch via ResultSet::getObject.
myPreparedStatement.setObject( … , instant );
If your JDBC driver does not comply, fall back to converting to java.sql.Timestamp. But minimize use of that class, only for talking to the database. Immediately convert back into java.time. Do not attempt business logic with Timestamp.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
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 java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
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.
Timestamp is unique and same every where in all timezones, which is value of new Date() in millis. What you are looking for here is formatted time of given timestamp (dt in above example.).
Date dt = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("IST time: " + format.format(dt));
format.setTimeZone(TimeZone.getTimeZone("Canada/Eastern"));
String parsedDate = format.format(dt);
System.out.println("Canada Time: " + parsedDate);
Output:
IST time: 2016-11-09 16:33:22
Canada Time: 2016-11-09 06:03:22
A Timestamp doesn't have a time zone in Java, it only represents a moment in time based on a number of milliseconds elapsed since a reference point, the epoch.
So it seems to me that you want your Timestamp to point to the current instant, which would be written very simply:
//with Java 8
Timestamp ts = Timestamp.from(Instant.now());
//or prior to Java 8:
Timestamp ts = new Timestamp(new Date().getTime());
You can set the TimeZone based on GMT. We know that Canada time is GMT-5,
so you can get the current Canada time like this:
TimeZone tz = TimeZone.getTimeZone("GMT-5");
Calendar c = Calendar.getInstance(tz);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA);
dateFormat.setTimeZone(tz);
System.out.println(dateFormat.format(c.getTime()));
Output: 2016-11-09 06:08:47
You need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
If you don't do this, the c.getTime() result will be your zone current time.
When I search online about "how to convert a Calendar to a String", all the results I find suggest to first convert to a Date and then convert the Date to a String.
The problem is that a Date is only a representation of the number of milliseconds since the epoch - it does not respect timezone. Calendar is more advanced in this way.
Of course, I could call the individual Calendar.get methods to create my own formatted string, but surely there must be an easier way?
To illustrate, I wrote this code:
long currentTime = Calendar.getInstance().getTimeInMillis();
Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
calendar.setTimeInMillis(currentTime);
System.out.println(calendar.getTime().toString());
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
While running this code from a machine based in London (UTC+0) at 8:02pm, I got the following results:
Wed Nov 18 20:02:26 UTC 2015
2015-11-18 20:02:26
21
The last line shows the real hour according to the calendar's timezone (Madrid which is UTC+1). It is 9:02pm in Madrid, but obviously both the native Date.toString as well as the DateFormat.format methods ignore the timezone because the timezone information is erased when calling Calendar.getTime (similarly Calendar.getTimeInMillis).
Given this, what is the best way to get a formatted string from a Calendar which respects timezone?
Set the timezone on the SimpleDateFormat object and then use z ..
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println(sdf.format(calendar.getTime());
See here for details on how to handle timezones in Java.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
Calendar cal = Calendar.getInstance();
System.out.println(simpleDateFormat.format(cal.getTime()));
java.time
While the other Answers appear to be correct, a better approach is to avoid using java.util.Date/.Calendar entirely.
Those old date-time classes have been superseded by the java.time framework built into Java 8 and later. 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.
Instant
An Instant represents a moment on the timeline in UTC.
Instant instant = Instant.now ( ); // Current moment in UTC.
For a given Calendar object, convert to an Instant using the method toInstant added in Java 8.
Instant instant = myCalendar.toInstant();
ZonedDateTime
You can assign a time zone (ZoneId) to an Instant to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "Europe/Madrid" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant, zoneId );
String Representation of Date-Time Value
Dump to console.
System.out.println ( "instant: " + instant + " adjusted into zone: " + zoneId + " is zdt: " + zdt );
The java.time classes use ISO 8601 standard formatting by default when parsing/generating String representations of date-time values. By default the ISO 8601 style is extended by appending the name of the time zone in addition to the usual offset-from-UTC.
instant: 2015-11-18T22:23:46.764Z adjusted into zone: Europe/Madrid is zdt: 2015-11-18T23:23:46.764+01:00[Europe/Madrid]
If you want the ISO 8601 style but without the T, either call .replace( "T" , "" ) on the resulting String object or define your own formatter.
The java.time.format package can do the work of determining a localized format appropriate to a particular Locale.
Locale locale = Locale.forLanguageTag ( "es-ES" );
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL );
String output = zdt.format ( formatter.withLocale ( locale ) );
miércoles 18 de noviembre de 2015 23H38' CET
You can use String.format() to avoid timezone problems
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
This example gives a result in the format: "yyyy-MM-dd HH:mm:ss"
Calendar c = Calendar.getInstance();
String s = String.format("%1$tY-%1$tm-%1$td:%1$tM:%1$tS", c);
System.out.println(s);
Output:
2015-11-20:44:55
I have 2 Strings
2012-06-25 15:02:22.948
+0530
I need a new string which adds the 5:30 to the time in the first string.
I thought I can do this by converting both strings to date objects and then adding. But i dont know how to do it, as when i use
yyyy MM dd hh:mm:ss as the date format for the first string, I get an error.
Thanks!
The format of the string 2012-06-25 15:02:22.948 is not yyyy MM dd hh:mm:ss, so it's not surprising that you get "an error" (what error is it? the more specific you are, the better people can help you!).
Try yyyy-MM-dd HH:mm:ss.SSS. See the API documentation of SimpleDateFormat to understand the exact syntax of the format string.
Note: Upper and lower case is important in the format string. hh means 12-hour clock, HH means 24-hour clock. If you use hh, parsing 15 for the hours won't work. You also didn't include the milliseconds SSS in the format string.
You can merge both you string String1+string2 and can use format yyyy-MM-dd HH:mm:ss.SSSZ to parse the date. You can see more documentation here
You're getting an exception because the your date format String is wrong. You're giving a date string on the form
"yyyy-MM-dd hh:mm:ss.S"
See SimpleDateFormat javadoc
Try this:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date date = format.parse("2012-06-25 15:02:22.948");
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(date.getTime());
int time = Integer.parseInt("0530");
int hour = time / 100;
int minute = time % 100;
calendar.add(Calendar.HOUR_OF_DAY, hour);
calendar.add(Calendar.MINUTE, minute);
String newDateInString = format.format(calendar.getTime());
The other answers are correct but outdated.
java.time
The old date-time classes (java.util.Date/.Calendar etc.) bundled with the earliest versions of Java are now legacy.
Those old classes have been supplanted by the java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
LocalDateTime
The LocalDateTime class represent a date-time without time zone. Use those for the first piece.
Your format is close to standard ISO 8601 format, just replace the SPACE with a T.
String input = "2012-06-25 15:02:22.948";
String inputStandardized = input.replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( inputStandardized );
Offset from UTC
The other piece is the offset-from-UTC. We use the ZoneOffset class for this.
ZoneOffset offset = ZoneOffset.of( "+0530" );
Without an offset or time zone the LocalDateTime is not an actual moment on the timeline but rather a rough idea about a possible moment. Now we add your offset-from-UTC to mark an actual moment, represented by the OffsetDateTime class.
OffsetDateTime odt = OffsetDateTime.of( ldt , offset );
Zoned
A time zone is an offset plus rules for handling anomalies such as Daylight Saving Time (DST). So better to use a time zone than a mere offset.
For example, if the context of this data is known to be time in India, use a time zone such as Asia/Kolkata to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId );
I am in need to manipulate on java.sql.Timestamp.
Input to the function is:
Formatted DateTime in java.sql.Timestamp
[Possible date formats are: MM/dd/yyyy hh:mm:ss aa, MM/dd/yyyy hh:mm:ss, MM/dd/yyyy hh:mm aa, MM/dd/yyyy HH:mm, MM/dd/yy hh:mm aa, MM/dd/yy HH:mm, MM/dd/yyyy, and some others]
Required Output:
java.sql.Timestamp in another Timezone the same formatted DateTime as input
So basically I need to change timezone of the DateTime in java.sql.Timestamp
I have seen other posts, which mention to use JODA, but I can't use it due to some restrictions.
I have tried
- to convert java.sql.Timestamp to java.date.Calendar,
- then change the timezone,
- then convert to it to date
- format date to the same formatted datetime
See the code below:
Timestamp ts = "2012-06-20 18:22:42.0"; // I get this type of value from another function
Calendar cal = Calendar.getInstance();
cal.setTime(ts);
cal.add(Calendar.HOUR, -8);
String string = cal.getTime().toString(); // return value is in " DAY MMM dd hh:mm:ss PDT yyyy " format i.e. Wed Jun 20 10:22:42 PDT 2012
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss"); // This could be any format required
Date date;
try {
date = formatter.parse(string); // I am getting exception here on parsing
} catch (ParseException e1) {
e1.printStackTrace();
}
Can anyone tell me what is wrong here, or is there any other way to manipulate on Timezone for java.sql.Timestamp ?
Thanks.
You are misunderstanding and abusing these classes.
Timestamp & Date have no time zone but UTC
manipulate on Timezone for java.sql.Timestamp
A java.sql.Timestamp is always a moment in UTC. No other time zone is involved, only UTC. Ditto for java.util.Date – always in UTC, no other time zone involved.
So your Question, as quoted above, does not make sense.
Timestamp & Date have no “format”
Neither Timestamp nor Date have a “format”. They use their own internally defined way to track the date-time. They are not strings, so they have no format. You can generate a String to represent their value in a particular format, but such a String is distinct and separate from the generating object.
java.time
You are using troublesome old date-time classes that wore supplanted years ago by the java.time classes.
Both Timestamp and Date are replaced by Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Your input is
String input = "2012-06-20 18:22:42.0" ;
That input is nearly compliant with standard ISO 8601 format. To comply fully, replace the SPACE in the middle with a T.
String input = "2012-06-20 18:22:42.0".replace( " " , "T" ) ;
Parse as a LocalDateTime because it lacks an indicator of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime, like your input string, does not represent a moment, is not a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. It represents only potential moments along a range of about 26-27 hours.
If you know the intended time zone, apply it to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
As for the other formats you mentioned, your Question is not at all clear. Search Stack Overflow for DateTimeFormatter class to see many examples and discussions of generating/parsing strings with the java.time classes. But first, get clear on the crucial concept that strings are not the date-time objects, and the date-time objects are not strings.
Database
If you were using java.sql.Timestamp to exchange data with a database, no need for that class anymore. As of JDBC 4.2 and later, you can directly exchange java.time objects with your database.
myPreparedStatement.setObject( … , instant ) ;
…and…
Instant instant = myResultSet.getObject( … , Instant.class ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Think of Timestamp as being a fixed point in time, disconnected from where on earth you happen to be looking at a clock.
If you want to display what's on the calendar/clock for a person at that instant in a particular time zone, you can set a calendar to that time zone and then associate your SimpleDateFormat to that calendar.
For example:
public void testFormat() throws Exception {
Calendar pacific = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
Calendar atlantic = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Timestamp ts = new Timestamp(System.currentTimeMillis());
sdf.setCalendar(pacific);
System.out.println(sdf.format(ts));
sdf.setCalendar(atlantic);
System.out.println(sdf.format(ts));
}
My output was:
2012-06-25 20:27:12.506
2012-06-25 23:27:12.506
I got it solved, I am putting code for reference.
Timestamp ts = "2012-06-20 18:22:42.0"; // input date in Timestamp format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Calendar cal = Calendar.getInstance();
cal.setTime(ts)
cal.add(Calendar.HOUR,-7); // Time different between UTC and PDT is -7 hours
String convertedCal = dateFormat.format(cal.getTime()); // This String is converted datetime
/* Now convert String formatted DateTime to Timestamp*/
SimpleDateFormat formatFrom = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
Date date = formatFrom.parse(convertedCal);
Timestamp finalTS = new Timestamp(date.getTime()); // Final value in Timestamp: 2012-06-20 11:22:42.0
} catch (Exception e) {
e.printStackTrace();
}
Couldn't you simply:
Get original time in milliseconds
Convert timezone difference to milliseconds
Add or subtract the difference from the original time.
Create a new timestamp using the new time in milliseconds
you miss one argumment in formatter.parse
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)
I have been developing Android application where I use this code:
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(d);
I need to get date after 8 hours from current moment, and I want that this date has 24-hours format, but I don't know how I can make it by SimpleDateFormat. I also need that date has DD/MM/YYYY HH:MM:SS format.
for 12-hours format:
SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("hh:mm", Locale.UK);
for 24-hours format:
SimpleDateFormat simpleDateFormatArrivals = new SimpleDateFormat("HH:mm", Locale.UK);
This will give you the date in 24 hour format.
Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
HH will return 0-23 for hours.
kk will return 1-24 for hours.
See more here: Customizing Formats
use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.
Use HH instead of hh in formatter string
tl;dr
The modern approach uses java.time classes.
Instant.now() // Capture current moment in UTC.
.truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
.plus( 8 , ChronoUnit.HOURS ) // Add eight hours.
.atZone( ZoneId.of( "America/Montreal" ) ) // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
.format( // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
.withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated.
) // Returns a `String` object.
23/01/2017 15:34:56
java.time
FYI, the old Calendar and Date classes are now legacy. Supplanted by the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).
Instant
Capture the current moment in UTC with the Instant class.
Instant instantNow = Instant.now();
instant.toString(): 2017-01-23T12:34:56.789Z
If you want only whole seconds, without any fraction of a second, truncate.
Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );
instant.toString(): 2017-01-23T12:34:56Z
Math
The Instant class can do math, adding an amount of time. Specify the amount of time to add by the ChronoUnit enum, an implementation of TemporalUnit.
instant = instant.plus( 8 , ChronoUnit.HOURS );
instant.toString(): 2017-01-23T20:34:56Z
ZonedDateTime
To see that same moment through the lens of a particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. 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 z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2017-01-23T15:34:56-05:00[America/Montreal]
Generate string
You can generate a String in your desired format by specifying a formatting pattern in a DateTimeFormatter object.
Note that case matters in the letters of your formatting pattern. The Question’s code had hh which is for 12-hour time while uppercase HH is 24-hour time (0-23) in both java.time.DateTimeFormatter as well as the legacy java.text.SimpleDateFormat.
The formatting codes in java.time are similar to those in the legacy SimpleDateFormat but not exactly the same. Carefully study the class doc. Here, HH happens to work identically.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );
Automatic localization
Rather than hard-coding a formatting pattern, consider letting java.time fully localize the generation of the String text by calling DateTimeFormatter.ofLocalizedDateTime.
And, by the way, be aware that time zone and Locale have nothing to do with one another; orthogonal issues. One is about content, the meaning (the wall-clock time). The other is about presentation, determining the human language and cultural norms used in presenting that meaning to the user.
Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" ); // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ); // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );
instant.toString(): 2017-01-23T12:34:56Z
zdt.toString(): 2017-01-24T01:34:56+13:00[Pacific/Auckland]
output: mardi 24 janvier 2017 à 01:34:56 heure avancée de la Nouvelle-Zélande
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….
Joda-Time
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Joda-Time makes this kind of work much easier.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );
System.out.println( "laterAsText: " + laterAsText );
When run…
laterAsText: 19/12/2013 02:50:18
Beware that this syntax uses default time zone. A better practice is to use an explicit DateTimeZone instance.
Try below code
String dateStr = "Jul 27, 2011 8:35:29 PM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse( dateStr );
} catch ( ParseException e ) {
e.printStackTrace();
}
String formattedDate = "";
if( date != null ) {
formattedDate = writeFormat.format( date );
}
System.out.println(formattedDate);
Good Luck!!!
Check for various formats.
All u need do is to change the lowercase 'hh' in the pattern to an uppercase letter 'HH'
for Kotlin:
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val currentDate = sdf.format(Date())
for java:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss") Date currentDate = sdf.format(new Date())
LocalDateTime#plusHours
LocalDateTime is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.
Use LocalDateTime#plusHours to get a copy of this LocalDateTime with the specified number of hours added.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the timezone of your JVM. It is also the
// default timezone for date-time type i.e.
// LocalDateTime.now(ZoneId.systemDefault()) is same as LocalDateTime.now().
// Change the timezone as per your requirement e.g. ZoneId.of("Europe/London")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldt);
LocalDateTime after8Hours = ldt.plusHours(8);
System.out.println(after8Hours);
// Custom format
DateTimeFormatter dtfTimeFormat24H = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss", Locale.ENGLISH);
DateTimeFormatter dtfTimeFormat12h = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
System.out.println(dtfTimeFormat24H.format(after8Hours));
System.out.println(dtfTimeFormat12h.format(after8Hours));
}
}
Output:
2021-01-07T15:24:52.736612
2021-01-07T23:24:52.736612
07/01/2021 23:24:52
07/01/2021 11:24:52 PM
Learn more about the modern date-time API from Trail: Date Time.
Using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date currentDateTime = calendar.getTime();
System.out.println(currentDateTime);
// After 8 hours
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date after8Hours = calendar.getTime();
System.out.println(after8Hours);
// Custom formats
SimpleDateFormat sdf24H = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
// Change the timezone as per your requirement e.g.
// TimeZone.getTimeZone("Europe/London")
sdf24H.setTimeZone(TimeZone.getDefault());
SimpleDateFormat sdf12h = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);
sdf12h.setTimeZone(TimeZone.getDefault());
System.out.println(sdf24H.format(after8Hours));
System.out.println(sdf12h.format(after8Hours));
}
}
Output:
Thu Jan 07 15:34:10 GMT 2021
Thu Jan 07 23:34:10 GMT 2021
07/01/2021 23:34:10
07/01/2021 11:34:10 PM
Some important notes:
A date-time object is supposed to store the information about date, time, timezone etc., not about the formatting. You can format a date-time object into a String with the pattern of your choice using date-time formatting API.
The date-time formatting API for the modern date-time types is in the package, java.time.format e.g. java.time.format.DateTimeFormatter, java.time.format.DateTimeFormatterBuilder etc.
The date-time formatting API for the legacy date-time types is in the package, java.text e.g. java.text.SimpleDateFormat, java.text.DateFormat etc.
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You can do it like this:
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy kk:mm:ss").format(d);
here 'kk:mm:ss' is right answer, I confused with Oracle database, sorry.
Try this...
Calendar calendar = Calendar.getInstance();
String currentDate24Hrs = (String) DateFormat.format(
"MM/dd/yyyy kk:mm:ss", calendar.getTime());
Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);