I am currently trying to get create a java Date which looks the same no matter what timezone I view it in. My current code is:
Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.JANUARY, 8, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
In my current timeZone this gives me '2015-01-08T00:00:00Z'In another this gives me 2015-01-08T00:00:00-03:00. What I want to know is if there is any way to drop the timezone part so as the time is the same in both time zones.
I would be VERY grateful for any help on this matter. Thank you.
Java SE 8 comes with a new Date & Time API. Have a look at LocalDate and LocalDateTime.
If you are only interested in the format of the time, create a java.text.SimpleDateFormat object to print your time in the format that you want.
http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
If you want the time to be printed with the same numbers no matter the TimeZone,
Use String ids[] = java.util.TimeZone.getAvailableIDs();
to get the TimeZone's IDs and find the ID that you want.
In this example, I created two SimpleDateFormat objects set to two different TimeZones. They both print off the same Calendar object. I have taken off the Z in ft2 to remove the time zone portion. By relying on toString(), I think you would be subject to Locale differences in displaying dates, like US MM/dd/yyyy and UK dd/MM/yyyy.
TimeZone tz = TimeZone.getTimeZone("America/New_York");
TimeZone tz2 = TimeZone.getTimeZone("America/Chicago");
Calendar acal = new GregorianCalendar();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd'T'hh:mm:ss Z");
ft.setTimeZone(tz);
SimpleDateFormat ft2 = new SimpleDateFormat ("yyyy-MM-dd'T'hh:mm:ss");
ft2.setTimeZone(tz2);
String date1 = ft.format(acal.getTime());
System.out.println(date1);
String date2 = ft2.format(acal.getTime());
System.out.println(date2);
Output:
2015-01-08T10:36:39 -0500
2015-01-08T09:36:39
Related
I have a string like this 210115 I want to represent it as 21:01:15 any ideas?.
I tried using Gregorian calendar but it adds date to it which I don't want
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date date = new Date();
try{
date = sdf.parse("210115");
}
catch(Exception e){
}
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.getTime());
Output is Thu Jan 01 21:01:15 UTC 1970 but what I want is just 21:01:15
Thanks.
To output a formatted date, you use another SimpleDateFormat object with a pattern with the format you want.
In this case, it sounds like you might want to use something like
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println( outputFormat.format(date) );
So what you want is just a time, without time zone. I would recommend using the LocalTime class, which is exactly that, instead of the Date class.
LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss"));
If u r getting the date string in "210115" this format and you want it in "21:01:15" format then why are you using date format.
Simply do string operation as:
String time="210115";
String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
System.out.println(newtime);
you will get the required format.21:01:15
How to reduce one month from current date and want to sore in java.util.Date variable
im using this code but it's shows error in 2nd line
java.util.Date da = new Date();
da.add(Calendar.MONTH, -1); //error
How to store this date in java.util.Date variable?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date result = cal.getTime();
Starting from Java 8, the suggested way is to use the Date-Time API rather than Calendar.
If you want a Date object to be returned:
Date date = Date.from(ZonedDateTime.now().minusMonths(1).toInstant());
If you don't need exactly a Date object, you can use the classes directly, provided by the package, even to get dates in other time-zones:
ZonedDateTime dateInUTC = ZonedDateTime.now(ZoneId.of("Pacific/Auckland")).minusMonths(1);
Calendar calNow = Calendar.getInstance()
// adding -1 month
calNow.add(Calendar.MONTH, -1);
// fetching updated time
Date dateBeforeAMonth = calNow.getTime();
you can use Calendar
java.util.Date da = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(da);
cal.add(Calendar.MONTH, -1);
da = cal.getTime();
Using new java.time package in Java8 and Java9
import java.time.LocalDate;
LocalDate mydate = LocalDate.now(); // Or whatever you want
mydate = mydate.minusMonths(1);
The advantage to using this method is that you avoid all the issues about varying month lengths and have more flexibility in adjusting dates and ranges. The Local part also is Timezone smart so it's easy to convert between them.
As an aside, using java.time you can also get the day of the week, day of the month, all days up to the last of the month, all days up to a certain day of the week, etc.
mydate.plusMonths(1);
mydate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).getDayOfMonth();
mydate.with(TemporalAdjusters.lastDayOfMonth());
Using JodaTime :
Date date = new DateTime().minusMonths(1).toDate();
JodaTime provides a convenient API for date manipulation.
Note that similar Date API will be introduced in JDK8 with the JSR310.
You can also use the DateUtils from apache common. The library also supports adding Hour, Minute, etc.
Date date = DateUtils.addMonths(new Date(), -1)
raduce 1 month of JDF
Date dateTo = new SimpleDateFormat("yyyy/MM/dd").parse(jdfMeTo.getJulianDate());
Calendar cal = Calendar.getInstance();
cal.setTime(dateTo);
cal.add(Calendar.MONTH, -1);
Date dateOf = cal.getTime();
Log.i("dateOf", dateOf.getTime() + "");
jdfMeOf.setJulianDate(cal.get(Calendar.DAY_OF_YEAR), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));
1.I want to set the setMaxSelectableDate=18years in JDateChooser so i provided it the date by incrementing milliseconds but how should i increment it by 18years.
2.Incrementing by 18years the calculation comes out to be 365*18*24*60*60*1000=56764800000 which gives me error integer number to large.
Date max=new Date();
Date oth1=new Date(max.getTime() + (365*18*24*60*60*1000)); //days*hours*minutes*seconds*milliseconds
SimpleDateFormat maxdateFormatter1 = new SimpleDateFormat("MMM d,yyyy hh:mm:ss a");
String maxdate=maxdateFormatter1.format(oth1);
DateChooser_V1.setMaxSelectableDate(new java.util.Date(maxdate));
Let java.util.Calendar do this work for you:
Calendar c = Calendar.getInstance();
c.setTime(oldDate);
c.add(Calendar.YEAR, 18);
Date newDate = c.getTime();
Which takes care of leap years, historical GMT offset changes, historical Daylight Saving Time schedule changes etc.
You need to use a long. You can achieve this by adding an L to your number:
365L* ...
With JodaTime
DateTime in18Years = new DateTime( ).plusYears( 18 );
Here is how to convert to java.util.Date
Date in18Years = new DateTime( ).plusYears( 18 ).toDate( );
You cannot willy-nilly add seconds (or millseconds) and expect calendar calculations to come out right. Basically it takes some extra effort to account for all of those leap-years, leap seconds, and daylight savings shifts.
Until Java 1.8 comes out, use java.util.Calendar instead of java.util.Date, there are really good reasons that java.util.Date has practically everything in it deprecated. While it looks good in the beginning, with enough use you will find it often "just doesn't work (tm)".
GregorianCalendar now = new GregorianCalendar();
now.add(Calendar.YEAR, 18);
And that's assuming that you didn't overflow Integer.MAX_INT.
I would use a Calendar object to achieve this:
Calendar cal = Calendar.getInstance();
Date dt = new Date();
...
// Set the date value
...
cal.setTime(dt);
cal.add(Calendar.YEAR, +18);
dt = cal.getTime();
Hope this helps you
I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html
How to convert Formatted date (yyyy-MM-dd) to Unix time in Java?
I want to declare a date using
Date birthday = new Date(y_birthday, m_birthday, d_birthday);
but this constructor has been deprecated, so I got to use the other constructor which uses Unix timestamp
So, you have the date as a string in the format yyyy-MM-dd? Use a java.text.SimpleDateFormat to parse it into a java.util.Date object:
String text = "2011-12-12";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(text);
edit If you need a java.sql.Date, then you can easily convert your java.util.Date to a java.sql.Date:
java.sql.Date date2 = new java.sql.Date(date.getTime());
Use a calendar object if you want more control of the date object
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 11); // indexed month (December)
calendar.set(Calendar.DATE, 12);
Date date = new Date(calendar.getTime().getTime());
The hours, minutes, seconds etc of the current time will be set though so you may want to set those to 0 (manually per field)
If you're using Java 7 then I think there's some much nicer stuff you can use for handling dates