Getting UTC time with Calendar and Date [duplicate] - java

This question already has answers here:
Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
(7 answers)
Closed 8 years ago.
I'm trying to get an instance of Date with UTC time using the following code:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date now = cal.getTime();
that looks so simple, but if I check the values at IntelliJ's debugger, I get different dates for cal and now:
cal:java.util.GregorianCalendar[time=1405690214219,areFieldsSet=true,lenient=true,zone=GMT,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=199,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=30,SECOND=14,MILLISECOND=219,ZONE_OFFSET=0,DST_OFFSET=0]
now:Fri Jul 18 10:30:14 BRT 2014
as you can see, cal is 3 hours ahead of now... what am I doing wrong?
Thanks in advance.
[EDIT] Looks like TimeZone.setDefault(TimeZone.getTimeZone("UTC")); before the code above does the job...

This question has already been answered here
The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.
You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
Edit To convert cal to date
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
System.out.println(year);
Date date = new Date(year - 1900, month, day); // is same as date = new Date();
Just build the Date object using the Cal values. Please let me know if that helps.

Try using a date formatter and set the time zone to UTC.
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));

Related

Need current date is in "UTC" timezone having Date format [duplicate]

This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(33 answers)
Closed 6 years ago.
I tried to convert current date is in "UTC" timezone format
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
DateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dat = sdf.format(cal.getTime());
System.out.println("In string format" + dat);
System.out.println(("Date After parses " + (Date) sdf.parse(dat)));
Below is op:
In string format Mon Apr 11 09:57:12 +0000 2016
Date After parses Mon Apr 11 15:27:12 IST 2016
When i tried to convert date(Parse) in Date Format from String,I am getting the date is in Current date time and also in IST format.
Try the solution explained in this post
Basically he gets the Calendar instance with the timeZone set as "UTC"
Here is the code:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTime(new Date());
DateFormat simpleDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

Convert SAS date value to Java YYYY-MM-DD

I have SAS date objects stored as integer and they look like : 19725.
I am trying to write java code to convert the date to YYYY-MM-DD
I see in the documentation that the SAS date value is the number of days from 01 Jan 1960
For example:
02 Jan 1960 would return 1
04 June 2003 would return 15680
Could you give the java code for this conversion. ie. convert something like 19725 to the date format : YYYY-MM-DD
I try the logic below but 15680 gives 2003-01-06 and not 2003-06-04 as the output. Could anyone point the mistake.Thanks in advance.
int numdays = 15680;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 1960);
cal.add(Calendar.DAY_OF_MONTH, numdays);
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Month are 0-based, so you're setting your calendar to February, not January. This should fix the issue:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.JANUARY);
// ...
In addition to RC's point about starting the month correctly with Calendar.JANUARY, your simpledateformat is wrong.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
'DD' is day of year (so 340th day of the year is Dec 6). 'dd' is day of the month. See the doc for more detail. (Also note that 15680 is Dec 6 2002, not what you say in the question.)
You may actually want to use 'yy' also:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
as 'YYYY' is "Week Year", which in some cases may differ from yyyy (calendar year) near the end of the year. See the docs for more details.
I like to use JodaTime for date manipulation like this.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusDays-int-
int sasDate = 19725;
DateTime base = new DateTime(1960, 1, 1, 0, 0);
DateTime computed = base.plusDays(sasDate);

JAVA : how to add extra time for timestamp [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 8 years ago.
Sorry im new to java, may i know how can i add extra time in here?
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String currTimestamp = timestampFormat.format(new Date());
System.err.println("currTimestamp=="+currTimestamp); // 2014/10/17 14:31:33
You can use Calender for this.
Calendar calendar=Calendar.getInstance(); // current time
System.out.println(calendar.getTime());
calendar.add(Calendar.MINUTE,3); // add 3 minutes to current time
System.out.println(calendar.getTime());
Out put:
Fri Oct 17 12:17:13 IST 2014
Fri Oct 17 12:20:13 IST 2014
Just as a comparison, using Java 8's new time API...
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
ldt = ldt.plusMinutes(3);
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
Or if you can't use Java 8, you could use the JodaTime API
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dt = DateTime.now();
System.out.println(timestampFormat.format(dt.toDate()));
dt = dt.plusMinutes(3);
Date date = dt.toDate();
System.out.println(timestampFormat.format(dt.toDate()));
Calander class have some useful methods to do this. If you want to still use Date it self, Add 3000 milliseconds to the current time.
String resultTime = timestampFormat.format(new Date(new Date().getTime() + 3000));
It would be better to use the Calendar class instead of using deprecated Date class:
Pull a Calendar instance:
Calendar c = Calendar.getInstance();
Add 3 minutes to the calendar current time:
c.add(Calendar.MINUTE, 3);
Format the new calendar time:
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String currTimestamp = timestampFormat.format(c.getTime());
System.err.println("currTimestamp==" + currTimestamp);

getting the wrong timezone in java / android [duplicate]

This question already has answers here:
Is java.util.Date using TimeZone?
(5 answers)
Closed 7 years ago.
String = 26/8/2013 15:59;
I want to convert this date into GMT, however after applying the below code, I get the EEST time rather than the GMT.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy h:m");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.parse(newDate);
Log.i(tag, df.parse(newDate).toString());
Output :
Mon Aug 26 18:59:00 EEST 2013
Whats wrong ?
Your parsing is correct, the different is just for your locale time zone that is used to display when you are making toString(). I just used formatted output to demonstrate the correct format . Here is the details example:
final String time = "26/8/2013 15:59";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(time);
// localDate.toString()
// PRINT. Mon Aug 26 15:59:00 EEST 2013
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
// PRINT. 26/08/2013 12:59
Nothing's really wrong. You are successfully parsing the datetime string interpreted as UTC timezone.
When printing it to log, you get what you ask for - Date.toString() returns the date formatted to current locale settings which include the timezone. The difference between UTC and EEST is 3 hours.
If you want to to format it to display some other timezone, pass it though format() of a SimpleDateFormat that is configured to the timezone you want.
I think you should use the below approach:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);

How to set a Java Date object's value to yesterday? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get yesterday's date using Date
What is an elegant way set to a Java Date object's value to yesterday?
With JodaTime
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minus(Period.days(1));
System.out.printf("Today is : %s, Yesterday : %s", today.toString("yyyy-MM-dd"), yesterday.toString("yyyy-MM-dd"));
Do you mean to go back 24 hours in time.
Date date = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);
or to go back one day at the time same time (this can be 23 or 25 hours depending on daylight savings)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
These are not exactly the same due to daylight saving.
Convert the Date to a Calendar object and "roll" it back a single day. Something like this helper method take from here:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime(c.getTime().getTime());
}
For your specific case, just pass in days as -1 and you should be done. Just make sure you take into consideration the timezone/locale if doing extensive date specific manipulations.
you can try the follwing code:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
As many people have already said use Calendar rather than date.
If you find you really want to use dates:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.getTime();//returns a Date object
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DAY_OF_MONTH, -1);
cal1.getTime();//returns a Date object
I hope this helps.
tomred
You can try the following example to set it to previous date.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today's date is " +dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));

Categories

Resources