I want to remove time from Date object.
DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format
But when I'm converting this date (which is in String format) it is appending time also.
I don't want time at all. What I want is simply "21/03/2012".
You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
The quick answer is :
No, you are not allowed to do that. Because that is what Date use for.
From javadoc of Date :
The class Date represents a specific instant in time, with millisecond precision.
However, since this class is simply a data object. It dose not care about how we describe it.
When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need.
There are many ways to do this.
Example 1 : by manipulating string
Input string : 2012/01/20 12:05:10.321
Desired output string : 2012/01/20
Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.
String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10); // Output : 2012/01/20
Example 2 : by SimpleDateFormat
Input string : 2012/01/20 12:05:10.321
Desired output string : 01/20/2012
In this case we want a different format.
String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012
For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.
Apache Commons DateUtils has a "truncate" method that I just used to do this and I think it will meet your needs. It's really easy to use:
DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);
DateUtils also has a host of other cool utilities like "isSameDay()" and the like. Check it out it! It might make things easier for you.
What about this:
Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = sdf.parse(sdf.format(today));
What you want is impossible.
A Date object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date object directly with System.out.println(date), it will always be formatted in a default format that includes the time. There is nothing you can do to change that.
Instead of somehow trying to use class Date for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat to format the date in whatever format you want.
The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.
Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate class would be what you'd use.
edit - note that my answer above is now more than 10 years old. If you are using a current version of Java (Java 8 or newer), then prefer to use the new standard date and time classes in package java.time. There are many classes available that represent just a date (day, month, year); a date and time; just a time; etc.
Date dateWithoutTime =
new Date(myDate.getYear(),myDate.getMonth(),myDate.getDate())
This is deprecated, but the fastest way to do it.
May be the below code may help people who are looking for zeroHour of the day :
Date todayDate = new Date();
GregorianCalendar todayDate_G = new GregorianCalendar();
gcd.setTime(currentDate);
int _Day = todayDate_GC.get(GregorianCalendar.DAY_OF_MONTH);
int _Month = todayDate_GC.get(GregorianCalendar.MONTH);
int _Year = todayDate_GC.get(GregorianCalendar.YEAR);
GregorianCalendar newDate = new GregorianCalendar(_Year,_Month,_Day,0,0,0);
zeroHourDate = newDate.getTime();
long zeroHourDateTime = newDate.getTimeInMillis();
Hope this will be helpful.
you could try something like this:
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
String s;
Format formatter;
Date date = new Date();
formatter = new SimpleDateFormat("dd/MM/yyyy");
s = formatter.format(date);
System.out.println(s);
}
}
This will give you output as21/03/2012
Or you could try this if you want the output as 21 Mar, 2012
import java.text.*;
import java.util.*;
public class DtTime {
public static void main(String args[]) {
Date date=new Date();
String df=DateFormat.getDateInstance().format(date);
System.out.println(df);
}
}
You can write that for example:
private Date TruncarFecha(Date fechaParametro) throws ParseException {
String fecha="";
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
fecha =outputFormatter.format(fechaParametro);
return outputFormatter.parse(fecha);
}
The correct class to use for a date without time of day is LocalDate. LocalDate is a part of java.time, the modern Java date and time API.
So the best thing you can do is if you can modify the getStartDate method you are using to return a LocalDate:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("en-IE"));
LocalDate d = eventList.get(0).getStartDate(); // We’re now getting a LocalDate using this method
String dateString = d.format(dateFormatter);
System.out.println(dateString);
Example output:
21/03/2012
If you cannot change the getStartDate, you may still be able to add a new method returning the type that we want. However, if you cannot afford to do that just now, convert the old-fashioned Date that you get (I assume java.util.Date):
d = eventList.get(0).getStartDate(); // I'm getting the old-fashioned Date using this method
LocalDate dateWithoutTime = d.toInstant()
.atZone(ZoneId.of("Asia/Kolkata"))
.toLocalDate();
Please insert the time zone that was assumed for the Date. You may use ZoneId.systemDefault() for the JVM’s time zone setting, only this setting can be changed at any time from other parts of your program or other programs running in the same JVM.
The java.util.Date class was what we were all using when this question was asked 6 years ago (no, not all; I was, and we were many). java.time came out a couple of years later and has replaced the old Date, Calendar, SimpleDateFormat and DateFormat. Recognizing that they were poorly designed. Furthermore, a Date despite its name cannot represent a date. It’s a point in time. What the other answers do is they round down the time to the start of the day (“midnight”) in the JVM’s default time zone. It doesn’t remove the time of day, only sets it, typically to 00:00. Change your default time zone — as I said, even another program running in the same JVM may do that at any time without notice — and everything will break (often).
Link: Oracle tutorial: Date Time explaining how to use java.time.
A bit of a fudge but you could use java.sql.Date. This only stored the date part and zero based time (midnight)
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2011);
c.set(Calendar.MONTH, 11);
c.set(Calendar.DATE, 5);
java.sql.Date d = new java.sql.Date(c.getTimeInMillis());
System.out.println("date is " + d);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("formatted date is " + df.format(d));
gives
date is 2011-12-05
formatted date is 05/12/2011
Or it might be worth creating your own date object which just contains dates and not times. This could wrap java.util.Date and ignore the time parts of it.
java.util.Date represents a date/time down to milliseconds. You don't have an option but to include a time with it. You could try zeroing out the time, but then timezones and daylight savings will come into play--and that can screw things up down the line (e.g. 21/03/2012 0:00 GMT is 20/03/2012 PDT).
What you might want is a java.sql.Date to represent only the date portion (though internally it still uses ms).
String substring(int startIndex, int endIndex)
In other words you know your string will be 10 characers long so you would do:
FinalDate = date.substring(0,9);
Another way to work out here is to use java.sql.Date as sql Date doesn't have time associated with it, whereas java.util.Date always have a timestamp.
Whats catching point here is java.sql.Date extends java.util.Date, therefore java.util.Date variable can be a reference to java.sql.Date(without time) and to java.util.Date of course(with timestamp).
In addtition to what #jseals has already said. I think the org.apache.commons.lang.time.DateUtils class is probably what you should be looking at.
It's method : truncate(Date date,int field) worked very well for me.
JavaDocs : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date, int)
Since you needed to truncate all the time fields you can use :
DateUtils.truncate(new Date(),Calendar.DAY_OF_MONTH)
If you are using Java 8+, use java.time.LocalDate type instead.
LocalDate now = LocalDate.now();
System.out.println(now.toString());
The output:
2019-05-30
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.
public static Date getZeroTimeDate(Date changeDate){
Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
return returnDate;
}
If the return value is not working then check for the context parameter in web.xml.
eg.
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
Don't try to make it hard just follow a simple way
date is a string where your date is saved
String s2=date.substring(0,date.length()-11);
now print the value of s2.
it will reduce your string length and you will get only date part.
Can't believe no one offered this shitty answer with all the rest of them. It's been deprecated for decades.
#SuppressWarnings("deprecation")
...
Date hitDate = new Date();
hitDate.setHours(0);
hitDate.setMinutes(0);
hitDate.setSeconds(0);
Related
I have a problem in displaying the date in my Application.
I am getting timestamp as:
2017-08-02T06:05:30.000Z
But as per this the actual time is:
2017:08:02 11:35 AM
But after converting using my code it displays the time as:
6:00 am
How to show it as current time?
My code is given below:
private static SimpleDateFormat timestampformat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'");
private static SimpleDateFormat sdftimeformat = new SimpleDateFormat("HH:mm a");
private static SimpleDateFormat getSdftimeformat() {
return sdftimeformat;
}
public static String timeStampConvertToTime(String time) {
Date date1 = null;
try {
date1 = timestampformat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedTime = getSdftimeformat().format(date1);
return formattedTime;
}
The first thing is that you're using mm:ss.mmm in your format. According to SimpleDateFormat javadoc, m represents the minutes, so you must change it to mm:ss.SSS because S represents the milliseconds.
Another detail is that the Z in the end is the timezone designator for UTC and it can't be ignored (at least it shouldn't). You must use the corresponding pattern for that, which is X:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
PS: the X pattern was introduced in Java 7. If you're using Java <= 6, the only alternative is to treat Z as a literal (an ugly workaround, I admit) and set the UTC as the timezone used by the parser:
// treat "Z" as literal
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// use UTC as timezone
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
With this, the date will have the value corresponding to 06:05 in UTC. To format the time to your timezone, you must use another SimpleDateFormat with the corresponding timezone:
// output format: hour:minute AM/PM
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
// assuming a timezone in India
outputFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println(outputFormat.format(date));
The output will be:
11:35 AM
If you don't set a timezone, it'll use the system's default. But the default can be changed without notice, even at runtime, so it's better to explicity set a specific timezone as above.
I also used java.util.Locale to set the language to English, because some locales can have different symbols for AM/PM. If you don't specify one, it'll use the system default and it's not guaranteed to be one in which the symbols are the ones you need (some locales uses "a.m./p.m." or another different formats, so it's better to use an explicit locale).
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To parse the input you can use the ZonedDateTime class, which has full support to timezones and it makes the conversion to another zones very easy. Then you use a DateTimeFormatter to format the output:
// parse the input
ZonedDateTime parsed = ZonedDateTime.parse("2017-08-02T06:05:30.000Z");
// convert to another timezone
ZonedDateTime z = parsed.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
// format output
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
System.out.println(fmt.format(z));
The output will be:
11:35 AM
If the input always has Z in the end, you can also use the Instant class:
// parse the input
Instant instant = Instant.parse("2017-08-02T06:05:30.000Z");
// convert to a timezone
ZonedDateTime z = instant.atZone(ZoneId.of("Asia/Kolkata"));
Note that I used hh for the hours: this will format using values from 1 to 12 (it makes sense because I'm also using the AM/PM designators). If you want values from 0 to 23, use HH instead - check the javadoc for more details.
Also note that the API uses IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or IST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
You can also use the system's default timezone with ZoneId.systemDefault(), but this can be changed without notice, even at runtime, so it's better to explicity use a specific one.
You need to use SimpleDateFormat class and specify the format you want to parse from , like this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
long timeStamp = sdf.parse('your_timestamp').getTime();
SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.getDefault());
String time =currentDateFormat.format(timeStamp); // Formatted time in string form
try this your will get result
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
// set your format in df variable
SimpleDateFormat df = new SimpleDateFormat(
"HH:mm a");
try {
cal.setTime('your value');
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String localtime = df.format(cal.getTime());
use this for get current time.
Calendar cal =
Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("HH:mm a");
// you can get seconds by adding "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
String localTime = date.format(currentLocalTime);
change time zone to your time zone
I assume the Z in Rose's timestamp is zulu time, it isn't really correct to hard code the conversion from zulu time to his local time zone (GMT+5:30 we are assuming). It might be OK if it is always returning Z but if it is
military time zones you would need something that can handle all the possible timezones.
This previous question implies there is no built in way to do it. Need to understand where the timestamp is coming from to really answer the question.
I am currently using SimpleDateFormat to create a datetime value in the format yyyy-MM-dd HH:mm:ss. Here is my code:
Date date = new SimpleDateFormat("yy-M-d H:m:ss").parse(datetime);
String Dtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
However I would like the format to be this instead:
2013-04-12T13:38:48+02:00
How can I add the timezone to get the desired format?
Thank you!
Have a look at the API documentation of SimpleDateFormat. There you can see, that you can use the character 'z' for the timezone information.
Example: "yyyy.MM.dd G 'at' HH:mm:ss z" will give you "2001.07.04 AD at 12:08:56 PDT"
To set the timezone on a date have a look at this question and the answers.
This is XML/XSD dateTime data type format. Use javax.xml.datatype.XMLGregorianCalendar
XMLGregorianCalendar gc = DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-04-12T13:38:48+02:00");
System.out.println(gc);
output
2013-04-12T13:38:48+02:00
If you use the 'z' or 'Z' then still you cannot be sure how your time zone will look like. It depends on your locals and JVM version which of the ISO8601 version will be chosen.
One of the way to have a timezone always in format "+02:00" is to request it. Use the following date format:
DateTimeFormatter formatter =
new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd'T'HH:mm:ss")
.appendOffset("+HH:MM","+00:00")
.toFormatter();
And use it always with the ZonedDateTime type. It is thread safe.
I have been looking for exactly the same answer. I have to be backward compatible to the existing date format, which is, like in the example - "2013-04-12T13:38:48+02:00" and my other limitation is that i cannot use any open source libraries other than what is provided with Java 6. Therefore, after not finding the solution here, I came up with this simple conversion technique, which is quite ugly, but i figured out i post it here in case someone needs a quick and dirty solution. If someone knows how to do it better (with the limitations i mentioned), please correct me.
Therefore, to produce the output in the desired format:
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public GregorianCalendar stringToCalendar(String v)
{
// 22 is an idx of last ':', you can replace with v.lastIndex(':') to be neat
String simpleV = v.substring(0, 22).concat(v.substring(23));
GregorianCalendar gc = (GregorianCalendar) df.getCalendar();
gc.setTime(df.parse(simpleV));
return gc;
}
public String calendarToString(GregorianCalendar v)
{
df.setCalendar(v);
String out = df.format(v.getTime());
return out.substring(0, 22).concat(":").concat(out.substring(22)); // read above on '22'
}
Like I said, this is far from perfect, but I did not find anything better..
There is a simple way of doing it. You can define your format like:
String Dtime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(date);
This should do it.
You easily achieve it by package java.util.Calendar
Try the following code
import java.util.Calendar; //Import package
String month_order[]={"Select...","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH) + 1;
int dom = cal.get(Calendar.DAY_OF_MONTH);
int doy=cal.get(Calendar.YEAR);
System.out.println("Current date: "+month_order[month]);
System.out.println("Current Month: "+dom);
System.out.println("Current year: "+doy);
I am having some issues in converting a calendar object to an XMLGregorian calendar in the format of YYYY-MM-DD HH:mm:ss.
My current code is:
Calendar createDate = tRow.getBasic().getDateCreated(0).getSearchValue();
Date cDate = createDate.getTime();
GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
which returns a date of 2013-01-03T11:50:00.000-05:00.
I would like it to read 2013-01-03 11:50:00.
I have checked a bunch of posts, which use DateFormat to parse a string representation of the date, however my dates are provided to me as a Calendar object, not a string.
I'd appreciate a nudge in the right direction to help me figure this one out.
An XMLGregorianCalendar has a specific W3C string representation that you cannot change.
However, you can format a Date with SimpleDateFormat.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = dateFormat.format(cDate);
You can get a Date object from a XMLGregorianCalendar object as follows:
xmlCalendar.getGregorianCalendar().getDate()
DateFormat#format takes a Object parameter. From memory, it should accept a Calendar object, if not, it WILL accept a Date object, so you could use Calendar#getTime as a worse case scenario
You can use a instance of SimpleDateFormat to specify a custom formatting. This will ensure that the result is always the same for different systems
Have you seen this tutorial it may help?
http://www.vogella.com/articles/JavaDateTimeAPI/article.html
Speicifcally this code is a good example:
// Format the output with leading zeros for days and month
SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMdd");
System.out.println(date_format.format(cal1.getTime()));
I want to convert the timestamp 2011-03-10T11:54:30.207Z to 10/03/2011 11:54:30.207. How can I do this? I want to convert ISO8601 format to UTC and then that UTC should be location aware. Please help
String str_date="2011-03-10T11:54:30.207Z";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
date = (Date)formatter.parse(str_date);
System.out.println("output: " +date );
Exception :java.text.ParseException: Unparseable date: "2011-03-10T11:54:30.207Z"
Firstly, you need to be aware that UTC isn't a format, it's a time zone, effectively. So "converting from ISO8601 to UTC" doesn't really make sense as a concept.
However, here's a sample program using Joda Time which parses the text into a DateTime and then formats it. I've guessed at a format you may want to use - you haven't really provided enough information about what you're trying to do to say more than that. You may also want to consider time zones... do you want to display the local time at the specified instant? If so, you'll need to work out the user's time zone and convert appropriately.
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2011-03-10T11:54:30.207Z";
DateTimeFormatter parser = ISODateTimeFormat.dateTime();
DateTime dt = parser.parseDateTime(text);
DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
System.out.println(formatter.print(dt));
}
}
Yes. you can use SimpleDateFormat like this.
SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String oldDate = "2011-03-10T11:54:30.207Z";
Date date = formatter.parse(oldDate.substring(0, 24));
FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println("OldDate-->"+oldDate);
System.out.println("NewDate-->"+FORMATTER.format(date));
Output
OldDate-->2011-03-10T11:54:30.207Z
NewDate-->10-Mar-2011 11:54:30.207
Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.
Pseudocode:
Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);
You might want to have a look at joda time, which is a little easier to use than the java native date tools, and provides many common date patterns pre-built.
In response to comments, more detail:
To do this using Joda time, you need two DateTimeFormatters - one for your input format to parse your input and one for your output format to print your output. Your input format is an ISO standard format, so Joda time's ISODateTimeFormat class has a static method with a parser for it already: dateHourMinuteSecondMillis. Your output format isn't one they have a pre-built formatter for, so you'll have to make one yourself using DateTimeFormat. I think DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS"); should do the trick. Once you have your two formatters, call the parseDateTime() method on the input format and the print method on the output format to get your result, as a string.
Putting it together should look something like this (warning, untested):
DateTimeFormatter input = ISODateTimeFormat.dateHourMinuteSecondMillis();
DateTimeFormatter output = DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS");
String outputFormat = output.print( input.parseDate(inputFormat) );
Hope this Helps:
public String getSystemTimeInBelowFormat() {
String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
return timestamp;
}
Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)
I need to create a java.util.Date object with an Australian timezone. this object is required for tag libraries used in downstream components (so I'm stuck with Date).
Here's what I have attempted:
TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
GregorianCalendar defaultDate = new GregorianCalendar(timeZone);
Date date = defaultDate.getTime();
However, "date" always returns the current local time (in my case, ET). What am I doing wrong here? Is it even possible to set a Date object with a different timezone?
Update:
Thanks for the responses! This works if I want to output the formatted date as a string, but not if I want to return a date object. Ex:
Date d = new Date();
DateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
String formattedDate = df.format(d); // returns Sydney date/time
Date myDate = df.parse(formattedDate); // returns local time(ET)
I think I'm going to end up reworking our date taglib.
Is it even possible to set a Date object with a different timezone?
No, it's not possible. As its javadoc describes, all the java.util.Date contains is just the epoch time which is always the amount of seconds relative to 1 january 1970 UTC/GMT. The Date doesn't contain other information. To format it using a timezone, use SimpleDateFormat#setTimeZone()
getTime is an Unix time in seconds, it doesn't have the timezone, i.e. it's bound to UTC. You need to convert that time to the time zone you want e.b. by using DateFormat.
import java.util.*;
import java.text.*;
public class TzPrb {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
System.out.println(df.format(d));
df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(df.format(d));
}
}