I have the following and I get the time back but I want to add hours to it. I'm not having luck. I have tried SimpleDateTime but cannot seem to get the syntax correct.
package com.sayitfast.service;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class TimeData {
private String time;
private Long milliseconds_since_epoch;
private String date;
#Override
public String toString() {
return "TimeData" + "time=" + time + ", milliseconds_since_epoch="
+ milliseconds_since_epoch + ", date=" + date;
}
public void TimeData() {
}
public void mytimdData() throws IOException {
String webPage = "http://time.jsontest.com";
InputStream is = nw URL(webPage).openStream();
final Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
Gson gson = new Gson();
TimeData td = gson.fromJson(reader, TimeData.class);
System.out.println(td.time);
}
}
You may need to add
String webPage = "http://time.jsontest.com";
InputStream is = new URL(webPage).openStream();
final Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
Gson gson = new Gson();
TimeData td = gson.fromJson(reader, TimeData.class);
System.out.println(td.toString());
System.out.println(td.getTime());
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(td.getTime());
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
Date dates = cal.getTime();
System.out.println(dates);
Here I have increased the time to 1hr. This is an example you can change as per your requirement
Also, you can use Date incrementedDate = DateUtils.addHour(date, 1); instead of Calender
I recommend you switch from the outdated and error-prone java.util date-time API to the rich set of modern date-time API and do it as follows (includes demo of some custom formats as well):
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(final String[] args) {
// Custom formats
DateTimeFormatter formatter24Hour = DateTimeFormatter.ofPattern("HH:mm:ss");
DateTimeFormatter formatter12Hour = DateTimeFormatter.ofPattern("hh:mm:ss a");
// Get the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
long epochMilli = Instant.now().toEpochMilli();
System.out.println("The number of milliseconds from the epoch is " + epochMilli);
System.out.println();
// Get Instant from the number of milliseconds from the epoch
Instant instant = Instant.ofEpochMilli(epochMilli);
// Get LocalDateTime from Instant
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());// Use the zone as per your requirement
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println("Date-time in your time-zone: " + ldt);
System.out.println("Time in your time-zone: " + ldt.format(DateTimeFormatter.ISO_LOCAL_TIME));
System.out.println("Time in your time-zone: " + ldt.format(formatter24Hour));
System.out.println("Time in your time-zone: " + ldt.format(formatter12Hour));
System.out.println();
// Add some hours e.g. 2 hours to LocalDateTime
LocalDateTime newDateTime = ldt.plus(2, ChronoUnit.HOURS);
System.out.println("Date-time in your time-zone after 2 hours: " + newDateTime);
}
}
Output:
The number of milliseconds from the epoch is 1593532251048
Date-time in your time-zone: 2020-06-30T16:50:51.048
Time in your time-zone: 16:50:51.048
Time in your time-zone: 16:50:51
Time in your time-zone: 04:50:51 pm
Date-time in your time-zone after 2 hours: 2020-06-30T18:50:51.048
Related
**I am trying to write the code for getting the date in required format , I have got the dates but how to add the required time with it ,
here I have
startDate - 1/08/2021 00:00:00 ,
EndDate - 20/08/2021 23:59:59 ,
increment days: 10
and the Expected output is :
05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,
This is the Code which I was trying to write , any help is appreciated
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DateTest {
public static List<LocalDate> getDaysBetweenDates(LocalDate startDate, LocalDate endDate, int interval) {
List<LocalDate> dates = new ArrayList<>();
while (endDate.isAfter(startDate)) {
dates.add(startDate);
startDate = startDate.plusDays(interval-1);
dates.add(startDate);
startDate = startDate.plusDays(1);
}
return dates;
}
public static void main(String[] args) {
int interval = 5;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss",Locale.US);
List<LocalDate> daysBetweenDates = getDaysBetweenDates(LocalDate.parse("01-08-2021 00:00:00", formatter),
LocalDate.parse("20-08-2021 23:59:59", formatter), interval);
System.out.println(daysBetweenDates);
}
}
Here's an alternative that uses LocalDates only (OK, and LocalDateTimes internally):
public static void printDaysInPeriod(LocalDate start, LocalDate end, int interval) {
// provide some data structure that
Map<LocalDate, LocalDate> intervals = new TreeMap<LocalDate, LocalDate>();
// loop through the dates in the defined period
while (start.isBefore(end)) {
// use the interval as step
LocalDate intervalEnd = start.plusDays(interval);
// store the sub-interval in the data structure
intervals.put(start, intervalEnd);
// and rearrange "start" to be the day after the last sub-interval
start = intervalEnd.plusDays(1);
}
// provide a formatter that produces the desired output per datetime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"dd/MM/uuuu HH:mm:ss"
);
// provide a data structure for the output parts (Strings here)
List<String> intervalOutput = new ArrayList<>();
// stream the sub-intervals
intervals.entrySet().forEach(e ->
// then produce the desired output per sub-interval and store it
intervalOutput.add(e.getKey().atStartOfDay()
.format(formatter)
+ " to "
+ e.getValue()
.atTime(LocalTime.MAX)
.format(formatter)));
// finally output the sub-interval Strings comma-separated
System.out.println(String.join(" , ", intervalOutput));
}
Using this method in a main, like this
public static void main(String[] args) {
// example dates defining an interval
String startInterval = "05/08/2021";
String endInterval = "15/08/2021";
// provide a parser that handles the format
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// then parse the dates to LocalDates
LocalDate start = LocalDate.parse(startInterval, dateParser);
LocalDate end = LocalDate.parse(endInterval, dateParser);
// and use the method
printDaysInPeriod(start, end, 5);
}
produces the following output:
05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 16/08/2021 23:59:59
You changed your questions a few times and in the first reading, I thought that you have start and end Date-Times as String. Based on this understanding, I wrote this answer. However, the very next minute, deHaar posted this correct answer. I am leaving this answer here for someone who will be looking for a solution to this kind of requirement (i.e. with Date-Time as String).
You can do it in the following two simple steps:
Define separate DateTimeFormatter for the input and the output strings
Loop through the parse range of Date-Time.
Demo
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strStartDateTime = "1/08/2021 00:00:00";
String strEndDateTime = "20/08/2021 23:59:59";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u H:m:s", Locale.ENGLISH);
LocalDateTime startDateTime = LocalDateTime.parse(strStartDateTime, dtfInput);
LocalDateTime endDateTime = LocalDateTime.parse(strEndDateTime, dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
for (LocalDateTime ldt = startDateTime, nextDateTime = ldt.plusDays(10).minusSeconds(1); !ldt
.isAfter(endDateTime); ldt = ldt.plusDays(10), nextDateTime = ldt.plusDays(10).minusSeconds(1))
System.out.println(dtfOutput.format(ldt) + " - " + nextDateTime);
}
}
Output:
2021-08-01 00:00:00 - 2021-08-10T23:59:59
2021-08-11 00:00:00 - 2021-08-20T23:59:59
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* 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.
Use the date-time API.
(The code should be self-explanatory.)
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DateTest {
public static List<ZonedDateTime> getDaysBetweenDates(ZonedDateTime startDate, ZonedDateTime endDate, int interval) {
List<ZonedDateTime> dates = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
dates.add(startDate);
if (Period.between(startDate.toLocalDate(), endDate.toLocalDate()).getDays() < interval) {
startDate = endDate;
}
else {
startDate = startDate.plusDays(interval);
}
dates.add(startDate);
startDate = startDate.plusDays(1);
}
return dates;
}
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
List<ZonedDateTime> dates = getDaysBetweenDates(ZonedDateTime.of(LocalDateTime.parse("05/08/2021 00:00:00", formatter), ZoneId.systemDefault()),
ZonedDateTime.of(LocalDateTime.parse("15/08/2021 23:59:59", formatter), ZoneId.systemDefault()),
5);
for (int i = 0; i < dates.size(); i+=2) {
System.out.printf("%s to %s , ",
dates.get(i).format(formatter),
dates.get(i + 1).format(formatter));
}
}
}
Output when running above code as follows:
05/08/2021 00:00:00 to 10/08/2021 00:00:00 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,
Given Format:
2017-03-08 13:27:00
I want to spilt it into 2 strings
1 for date and 1 for time
for
E.g.
08-03-2017
13:27:00
First if your date in String format then Parse it to Date and then try it.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date today = new Date();
DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
timeFormat.format(today);
dateFormat.format(today);
System.out.println("Time: " + timeFormat.format(today));
System.out.println("Date: " + dateFormat.format(today));
}
}
Output:
Time: 1:25:31 AM
Date: 31 Mar, 2017
Hope this help !
try this
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormateDate {
public static void main(String[] args) throws ParseException {
String date_s = "2017-03-08 13:27:00";
// *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(date_s);
// *** same for the format String below
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date :"+dt1.format(date));
dt1 = new SimpleDateFormat("HH:mm:ss");
System.out.println("Time :"+dt1.format(date));
}
}
It gives output like this
Date :2017-03-08 Time :13:27:00
Try this :
String datetime= "2017-03-08 13:27:00";
String[] divide= datetime.split("\\s");
String date = divide[0]; //2017-03-08
String time= divide[1]; // 13:27:00
I have a Joda-Time DateTime object and need to have date and time separately, with time zone label at the end:
DateTime dateTime = new DateTime();
System.out.println(dateTime.toString("YYYY-MM-ddZ"));
System.out.println(dateTime.toString("HH:mm:ssZ"));
In this case the output will be:
2014-02-27+0000
15:10:36+0000
Almost exactly what I need, but it is possible to have it like this?
2014-02-27Z
15:10:36Z
Here's a working example
DateTime dateTime = new DateTime();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd")
.appendTimeZoneOffset("Z", false, 2, 2)
.toFormatter();
System.out.println(formatter.print(dateTime.withZone(DateTimeZone
.forID("Zulu"))));
Basically, if the time zone offset is zero, you print Z. Since Zulu or UTC has an offset of 0, that's what will be printed.
If you're trying to use Military codes (i.e. Z for GMT see: http://www.timeanddate.com/library/abbreviations/timezones/military/z.html) you could so something like this:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Date;
public class CalendarExample {
static final String MILITARY_OFFSETS = "YXWVUTSRQPONZABCDEFGHIKLM";
static final int MILLIS_IN_HOUR = 1000*60*60;
public static void main(String[] args) {
System.out.println(formatDate(new Date(), "yyyy-MM-dd", "GMT")); // 2014-02-27Z
System.out.println(formatDate(new Date(), "HH:mm:ss", "GMT"));
System.out.println(formatDate(new Date(), "yyyy-MM-dd", "EST"));
System.out.println(formatDate(new Date(), "HH:mm:ss", "EST"));
}
static String formatDate(Date date, String dateTimeFormat, String timezoneCode) {
Calendar calendar = new GregorianCalendar();
TimeZone tz = TimeZone.getTimeZone(timezoneCode);
calendar.setTimeZone(tz);
int offset = calendar.get(Calendar.ZONE_OFFSET)/MILLIS_IN_HOUR;
// System.out.println(timezoneCode + " Offset is " + offset + " hours");
String timeZoneCode = MILITARY_OFFSETS.substring(offset + 12, offset + 13);
SimpleDateFormat dateFmt = new SimpleDateFormat(dateTimeFormat + "'" + timeZoneCode + "'");
return dateFmt.format(date);
}
}
output:
2014-02-27Z
11:57:44Z
2014-02-27R
11:57:44R
Try this
DateTime dateTime = new DateTime();
System.out.println(dateTime.toString("YYYY-MM-dd z");
System.out.println(dateTime.toString("HH:mm:ss z");
Use "z" instead of "Z".
Time zone ids of Joda Time can simply be displayed with the following segment of code.
Set<String> zoneIds = DateTimeZone.getAvailableIDs();
for(String zoneId:zoneIds) {
System.out.println(zoneId);
}
But how to display the corresponding timezone offset, timezone ID, and long name so that the list could look something like the following?
(GMT-10:00) Pacific/Honolulu, Hawaii Standard Time
(GMT-10:00) Pacific/Johnston, Hawaii Standard Time
(GMT-10:00) Pacific/Fakaofo, Tokelau Time
(GMT-10:00) HST, Hawaii Standard Time
They are needed to list in a drop-down-box for selection.
The following snippet shows the names but the offset it displays looks wonky.
Set<String> zoneIds = DateTimeZone.getAvailableIDs();
for (String zoneId : zoneIds) {
int offset = DateTimeZone.forID(zoneId).getOffset(new DateTime());
String longName = TimeZone.getTimeZone(zoneId).getDisplayName();
System.out.println("(" + offset + ") " + zoneId + ", " + longName);
}
Out of the long list it displays, a few of them are shown like,
(-36000000) Pacific/Honolulu, Hawaii Standard Time
(-36000000) Pacific/Johnston, Hawaii Standard Time
(-36000000) Pacific/Fakaofo, Tokelau Time
(-36000000) HST, Hawaii Standard Time
The offset should be as shown in this list.
The following approach worked.
import java.util.Set;
import java.util.TimeZone;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
Set<String> zoneIds = DateTimeZone.getAvailableIDs();
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("ZZ");
for (String zoneId : zoneIds) {
String offset = dateTimeFormatter.withZone(DateTimeZone.forID(zoneId)).print(0);
String longName = TimeZone.getTimeZone(zoneId).getDisplayName();
System.out.println("(" + offset + ") " + zoneId + ", " + longName);
}
There could also be other and probably better ways that I'm right now unaware of.
Or
import java.util.Set;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
Set<String> zoneIds = DateTimeZone.getAvailableIDs();
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("ZZ");
for (String zoneId : zoneIds) {
String offset = dateTimeFormatter.withZone(DateTimeZone.forID(zoneId)).print(0);
String longName = DateTimeZone.forID(zoneId).getName(DateTimeUtils.currentTimeMillis());
System.out.println("(" + offset + ") " + zoneId + ", " + longName);
}
For Greenwich Mean Time (Etc/GMT+0, for example), it would display, for example +00:00 instead of displaying GMT+00:00 as in the first case.
If the name is not available for the locale, then this method (public final String getName(long instant)) returns
a string in the format [+-]hh:mm.
An appropriate Locale can also be used, if needed using the overloaded method,
public String getName(long instant, Locale locale)
Short names, for example UTC for Coordinated Universal Time can be displayed as follows.
import java.util.Set;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
Set<String> zoneIds = DateTimeZone.getAvailableIDs();
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("ZZ");
for (String zoneId : zoneIds) {
String offset = dateTimeFormatter.withZone(DateTimeZone.forID(zoneId)).print(0);
String shortName = DateTimeZone.forID(zoneId).getShortName(DateTimeUtils.currentTimeMillis());
System.out.println("(" + offset + ") " + zoneId + ", " + shortName);
}
With an appropriate Locale, if needed using the overloaded method,
public String getShortName(long instant, Locale locale)
Update :
Using the Java Time API in Java SE 8 in which this is further simplified.
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
for (String zoneId : zoneIds) {
ZoneId zone = ZoneId.of(zoneId);
ZonedDateTime zonedDateTime = ZonedDateTime.now(zone);
ZoneOffset offset = zonedDateTime.getOffset();
String longName = zone.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println("(" + offset + ") " + zoneId + ", " + longName);
}
The display name has various styles available in java.time.format.TextStyle. For example, abbreviations can be displayed using TextStyle.SHORT.
zone.getDisplayName(TextStyle.FULL, Locale.ENGLISH) will display long names like "India Time". This is however, not a full name unlike Joda Time.
The following will display a full name of the given name like "India Standard Time" (wherever applicable).
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("zzzz");
String longName = pattern.format(ZonedDateTime.now(ZoneId.of(zoneId)));
The following will display a zone-offset of the given zone like GMT+05:30 (note the capitalization of the pattern).
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("ZZZZ");
String longName = pattern.format(ZonedDateTime.now(ZoneId.of(zoneId)));
The following is for displaying abbreviations.
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("zzz");
String longName = pattern.format(ZonedDateTime.now(ZoneId.of(zoneId)));
Capital ZZZ for zone-offset like +0530, +0000.
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.time.zone.ZoneRules;
import java.util.Locale;
import java.util.TimeZone;
// Europe/Berlin
// Europe/London
// Asia/Kolkata
public class TimeZoneTest {
public static void main(String[] args) {
ZonedDateTime timeZone = ZonedDateTime.of(LocalDateTime.of(2020, 8, 06, 05, 45),
ZoneId.of("Asia/Manila"));
Instant instant = timeZone.toInstant();
ZoneRules rules = timeZone.getZone().getRules();
boolean isDst = rules.isDaylightSavings(instant);
String dstShortName = DateTimeFormatter.ofPattern("zzz").format(timeZone);
String dstLongName = DateTimeFormatter.ofPattern("zzzz").format(timeZone);
TimeZone tz = TimeZone.getTimeZone(timeZone.getZone());
System.out.println(timeZone.getZone().getId());
System.out.println(timeZone.getOffset().getTotalSeconds()); //Offset
System.out.println(rules.getStandardOffset(instant).getTotalSeconds()); //RawOffset
System.out.println((rules.getDaylightSavings(instant).getSeconds())); //DstSavings
System.out.println(rules.isDaylightSavings(instant));
System.out.println(dstShortName);
System.out.println(dstLongName);
if (isDst) {
//Set standard timezone name
System.out.println(timeZone.getZone().getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
System.out.println(timeZone.getZone().getDisplayName(TextStyle.FULL, Locale.ENGLISH));
} else {
//Set DST timezone name
System.out.println(tz.getDisplayName(true, TimeZone.SHORT, Locale.ENGLISH));
System.out.println(tz.getDisplayName(true, TimeZone.LONG, Locale.ENGLISH));
}
// //SHORT: CEST
// DateTimeFormatter.ofPattern("zzz").format(zonedDateTime)
//
// //SHORT: CET
// ZoneId.getDisplayName(TextStyle.SHORT,Locale.ENGLISH)
//
// //LONG: Central European Summer Time
// DateTimeFormatter.ofPattern("zzzz").format(zonedDateTime)
//
// //LONG: Central European Time
// ZoneId.getDisplayName(TextStyle.LONG,Locale.ENGLISH)
//
// //Use this for converting CET to CEST and vice versa
// TimeZone tz = TimeZone.getTimeZone(timeZone.getZone());
// tz.getDisplayName(true, TimeZone.SHORT, Locale.ENGLISH));
//Joda
// DateTimeZone dz = DateTimeZone.forID("Asia/Manila");
// String shortName = dz.getShortName(DateTimeUtils.currentTimeMillis());
// System.out.println(shortName);
//
// String longerName = dz.getName(DateTimeUtils.currentTimeMillis());
// System.out.println(longerName);
}
}
I want to get local time of different time zones using Java code. Based on the time zone passed to the function I need that time zone's local time. How to achieve this?
java.util.TimeZone tz = java.util.TimeZone.getTimeZone("GMT+1");
java.util.Calendar c = java.util.Calendar.getInstance(tz);
System.out.println(c.get(java.util.Calendar.HOUR_OF_DAY)+":"+c.get(java.util.Calendar.MINUTE)+":"+c.get(java.util.Calendar.SECOND));
I'd encourage you to check out Joda Time, an alternative (but very popular) to the standard Java date and time API:
http://joda-time.sourceforge.net/index.html
Using Joda Time, I think this is what you what:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class TimeZoneDemo {
public static void main(String[] args) {
DateTime now = new DateTime(System.currentTimeMillis(), DateTimeZone.forID("UTC"));
System.out.println("Current time is: " + now);
}
}
You just need to know the standard ID for the time zone in question, such as UTC.
Java 1.8 provides you with some new classes in package java.time:
package learning.java8;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.junit.Test;
public class JavaTimeLT {
#Test
public void zonedDataTimeExample() {
final ZoneId zoneId = ZoneId.of("Europe/Zurich");
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), zoneId);
System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
}
I wrote the following program to get time for all the Timezones available, see if this helps...
String[] zoneIds = TimeZone.getAvailableIDs();
for (int i = 0; i < zoneIds.length; i++) {
TimeZone tz = TimeZone.getTimeZone(zoneIds[i]);
System.out.print(tz.getID() + " " + tz.getDisplayName());
Calendar calTZ = new GregorianCalendar(tz);
calTZ.setTimeInMillis(new Date().getTime());
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, calTZ.get(Calendar.YEAR));
cal.set(Calendar.MONTH, calTZ.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, calTZ.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, calTZ.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, calTZ.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, calTZ.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, calTZ.get(Calendar.MILLISECOND));
System.out.println( " "+cal.getTime());
check this. hope it will help.
TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
Calendar cal = Calendar.getInstance();
int LocalOffSethrs = (int) ((cal.getTimeZone().getRawOffset()) *(2.77777778 /10000000));
int ChinaOffSethrs = (int) ((tz.getRawOffset()) *(2.77777778 /10000000));
TimeZone tz1 = TimeZone.getTimeZone("US/Central");
String ss =cal.getTimeZone().getDisplayName();
System.out.println("Local Time Zone : " + ss);
System.out.println("China Time : " + tz.getRawOffset());
System.out.println("Local Offset Time from GMT: " + LocalOffSethrs);
System.out.println("China Offset Time from GMT: " + ChinaOffSethrs);
cal.add(Calendar.MILLISECOND,-(cal.getTimeZone().getRawOffset()));
//cal.add(Calendar.HOUR,- LocalOffSethrs);
cal.add(Calendar.MILLISECOND, tz.getRawOffset());
Date dt = new Date(cal.getTimeInMillis());
System.out.println("After adjusting offset Acctual China Time :" + dt);
In Java 8, you can use the ZonedDateTime.now(ZoneId zone) method:
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
LocalTime localTime = zonedDateTime.toLocalTime();
System.out.println(localTime);
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
SimpleDateFormat dateFormat = new SimpleDateFormat();
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
GregorianCalendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 0);
System.out.println(dateFormat.format( cal.getTime()));