Convert IST to PST in java - java

Hi
I have a date/Time field i want to get Convert current IST to CURRENT PST in java... need help....
ex: now in IST its :13/may/2011 3.32.58pm want the same in PST i.e. 13/may/2011 3.02.58 AM
thank you........

If you're interested in the current time, you don't need to know about IST at all... just the current instance, and the conversion to PST. You can do this with something like:
Date now = new Date();
TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); // For example...
DateFormat format = new SimpleDateFormat("..."); // Put your pattern here
format.setTimeZone(zone);
String text = format.format(now);
Personally I'd recommend you use Joda Time for all date/time work instead, as it's a much nicer API - but in this case it's really pretty simple even with the built-in API.

The Answer by Jon Skeet is correct but now outdated with the arrival of the java.time code in Java 8 and later.
java.time
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).
Get current moment in UTC.
Instant instant = Instant.now();
Adjust into a time zone.
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/Los_Angeles" );
ZonedDateTime zdt = instant.atZone( z );
To generate a String in standard ISO 8601 format, call the toString. For alternate formatting, use the DateTimeFormatter class already covered in many other Questions and Answers.
String output = zdt.format( myDateTimeFormatter );
See the same moment in India time, specifically Asia/Kolkata.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata );
I am not sure if by IST you meant India Standard Time or Irish Standard Time. Let's cover Europe/Dublin as well. That zone happens to currently use an offset of zero, +00:00. So its wall-clock time in the same as UTC.
ZoneId zDublin = ZoneId.of( "Europe/Dublin" );
ZonedDateTime zdtDublin = zdt.withZoneSameInstant( zDublin );
See this code run live at IdeOne.com.
instant.toString(): 2017-02-13T07:28:57.738Z
zdt.toString(): 2017-02-12T23:28:57.738-08:00[America/Los_Angeles]
zdtKolkata.toString(): 2017-02-13T12:58:57.738+05:30[Asia/Kolkata]
zdtDublin.toString(): 2017-02-13T07:28:57.738Z[Europe/Dublin]
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 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 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.

Related

something about the result of Date(long date )

The JDK1.8 API saies the result of the Date(long date) is based on the time January 1, 1970, 00:00:00 GMT, but when I test it by set the date=0, I find the result is not the Thu Jan 01 08:00:00 CST 1970, it's not the 00:00:00,but the 08:00:00,why?the result about the Date(long date)
It's because of your timezone.
If you change the time zone to GMT it will show 00:00:00
Date date = new Date(0L);
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
System.out.println(date);
Output : Thu Jan 01 00:00:00 GMT 1970
tl;dr
Instant.EPOCH.toString()
1970-01-01T00:00:00Z
Instant.EPOCH.atZone( ZoneId.of( "America/Chicago" ) ).toString() // Use proper time zone names (continent/region). Avoid pseudo-zones such as `CST`, which could be Central Standard Time in US or China Standard Time.
1969-12-31T18:00-06:00[America/Chicago]
Instant.EPOCH.atZone( ZoneId.of( "Asia/Hong_Kong" ) ).toString()
1970-01-01T08:00+08:00[Asia/Hong_Kong]
Avoid legacy date-time classes
You are using you using old date-time classes, now legacy, supplanted by the java.time classes.
Among its many problems, the toString method of java.util.Date implicitly applies the JVM’s current default time zone while generating a string. Avoid this class.
java.time
Instead use Instant. Represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant.ofEpochSecond( 0 ).toString()
1970-01-01T00:00:00Z
Or use the constant for that value, Instant.EPOCH.
For current moment in UTC, call now.
Instant.now()
To adjust into a specific time zone, search Stack Overflow for ZonedDateTime and ZoneId.
Adjust into another time zone. Same moment, same simultaneous point on the time line, but different wall-clock time.
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( "Asia/Hong_Kong" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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.
It is because of the TimeZone set, by default by the JVM when & where you run the program, look at the below statement from the Java doc.
Typically, you get a TimeZone using getDefault which creates a
TimeZone based on the time zone where the program is running. For
example, for a program running in Japan, getDefault creates a TimeZone
object based on Japanese Standard Time.
You can look at here

Java Date Format Parsing

I am trying to change the date format from a JSON response, but I keep getting java.text.ParseException.
This is the date from the server 2015-02-03T08:37:38.000Z and I want it to show as 2015/02/03 That's yyyy-MM-dd. And I did this.
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
String dateResp = transactionItem.get(position).getDate();
try {
Date date = df1.parse(dateResp);
transDate.setText(dateFormatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
But the exception keeps showing.
You must escape the Z:
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Try to use this for formatting purpose instead of your provided formatting string. It should work nicely :)
tl;dr
Instant.parse( "2015-02-03T08:37:38.000Z" )
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.toString() // 2015-02-03
Using java.time
The modern way to handle date-time work is with the java.time classes.
Your input string format happens to comply with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern at all.
Parse that string as an 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.parse( "2015-02-03T08:37:38.000Z" ) ;
To extract a date, you must specify a time zone. For any given moment the date varies around the globe by zone. For example, a moment after midnight in Paris France is a new day while still “yesterday” in Montréal Canada.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You want only the date portion without the time of day. So extract a LocalDate. While a LocalDate lacks any concept of offset-from-UTC or time zone, the toLocalDate method respects the ZonedDateTime object’s time zone in determining the date.
LocalDate ld = zdt.toLocalDate();
You seem to want standard ISO 8601 format, YYYY-MM-DD. Simply call toString without need to specify a formatting pattern.
String output = ld.toString();
2015-02-03
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 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 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.

Reading system time in CST time zone using Java

I am trying to read the system date in CST time zone using Java. I tried the below code but whenever I use formatter.parse() it is returning time in EST time zone.
private Date getTodayInCST() {
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
String today = formatter.format(currentdate.getTime());
try {
return formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
tl;dr
ZonedDateTime.now(
ZoneId.of( "America/Chicago" )
)
Details
I am trying to read the system date in CST time zone
By “CST”, do you mean Central Standard Time in North America, or China Standard Time?
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 as seen above with CST.
ZoneId z = ZoneId.of( "America/Chicago" ) ;
java.time
You are using troublesome old date-time classes that are now legacy. Supplanted by the java.time classes.
Get the current moment in UTC. 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() ;
2018-02-26T05:45:24.213610Z
Adjust into another time zone. Same moment, same point on the timeline, different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-02-25T23:45:24.213610-06:00[America/Chicago]
The above strings are in standard ISO 8601 format. The ZonedDateTime class extends that standard wisely to append the name of the zone in square brackets.
If you want to generate String objects in other formats, use DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
String output = zdt.format( f ) ;
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.
java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
If you want to set timezone try it this way
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
format.setTimeZone(TimeZone.getTimeZone("CST"));
System.out.println(format.format(new Date()));
If want to the code to provide the current time considering the daylight saving adjustment from CST to CDT or vice versa ,you can use the
"CST6CDT" timezone. in place of "CST" in SimpleDateFormat.
SimpleDateFormat cstCdtFormat=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
cstCdtFormat.setTimeZone(TimeZone.getTimeZone("CST6CDT"));
System.out.println(cstCdtFormat.format(new Date()));

Setting DateFormat to current date and time

I am using java.text.DateFormat in order to display the date and time for a user of my application. Below is my code to test the output.
The issue is that the date is being displayed as 1970 (see output below). How can I update this to the current date and time.
Current Output:
1 Jan 1970 01:00:00
Current code:
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateTimeInstance(),
};
for (DateFormat df : formats) {
Log.d("Dateformat", "Date format: " + (df.format(new Date(0))));
}
Alternatively if the above is not possible, I am able to get the current time and date using the following method:
Time now = new Time();
now.setToNow();
String date= now.toString();
Output:
20140722T133458Europe/London(2,202,3600,1,1406032498)
How can I adjust this in order to make it readable for a user?
Just write new Date() instead of new Date(0) in your first snippet. When you write new Date(some number) it makes a date which is that many milliseconds after 1/1/1970 00:00:00Z
Use this -
String S = new SimpleDateFormat("MM/dd/yyyy").format(System.currentTimeMillis());
tl;dr
Instant.now()
.atZone( ZoneId.of( "America/Montreal" ) )
.format( DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
)
Instant
The accepted Answer by Wallace is correct.
But know that you are using troublesome old date-time classes now supplanted by the java.time classes.
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(); // Current moment in UTC.
To generate a String representing that moment formatting according to the ISO 8601 standard, simply call toString.
ZonedDateTime
To view the same moment through the lens of some region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z ); // Adjust from UTC to a specific time zone. Same moment, different wall-clock time.
DateTimeFormatter
For presentation to the user, let java.time automatically localize using the DateTimeFormatter class.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
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, & java.text.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.

add more than 30 days with Calendar's add() method in Java

I'm not quite sure what field to use when adding more than 30 days to a Java Calendar object. Is there any difference in between Calendar.DAY_OF_MONTH and Calendar.DAY_OF_YEAR?
Example:
GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.DAY_OF_YEAR, 90);
vs
GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.DAY_OF_MONTH, 90);
Thanks.
I don't think it makes a difference when you call add. The distinction is important when you call the getters.
Both methods work fine, right? For more than 30 days, as well as negative amounts.
The (admittedly complicated) source for GregorianCalendar#add has this section:
case DAY_OF_MONTH: // synonym of DATE
case DAY_OF_YEAR:
case DAY_OF_WEEK:
break;
tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.plusDays( 30 )
Details
Much easier now with the modern java.time classes that supplant the old Calendar & Date classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
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" );
LocalDate today = LocalDate.now( z );
You can add a number of days to that.
LocalDate later = today.plusDays( 30 );
Period
You can represent a span of time with the Period class.
Period thirtyDays = Period.ofDays( 30 );
You can perform date math by calling plus or minus methods.
LocalDate later = today.plus( thirtyDays );
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 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 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.

Categories

Resources