This question already has answers here:
Convert date to different timezone [duplicate]
(3 answers)
Closed 5 years ago.
I have the following code:
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(date);
When I call this code with a date object, then it returns the same date (as String obviously) without setting the timezone.
As I understood a java.util.Date object is timezone independent. So if I set the timezone on the SimpleDateFormat then it should change. But it doesn't.
If I check sdf.getTimeZone() then I see that my timezone is set correctly to UTC+03:00.
Does someone know how to solve this problem?
To get the TimeZone in UTC Format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return simpleDateFormat.format(new Date());
the above format gives results as 22-10-2017 18:05:50 UTC.
To get the TimeZone in Local Format (TimeZone of Phone or device)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);
simpleDateFormat.setTimeZone(TimeZone.getDefault());
return simpleDateFormat.format(new Date());
or
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);
return simpleDateFormat.format(new Date());
the above format gives results as 22-10-2017 18:05:50 UTC+5:30.(Hint:-For India)
or
the above format gives results as 22-10-2017 18:05:50 IST.(Hint:-For India)
Hint : - if u pass this formatted String to Date like below
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-YYY HH:mm:ss Z",Locale.ENGLISH);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = null;
try {
d =simpleDateFormat.parse("22-10-2017 18:05:50 UTC");
} catch (ParseException e) {
e.printStackTrace();
}
return d.toString();
the returned output will be same as device timezone i.e local Timezone or default timezone . (22-10-2017 18:05:50 UTC+5:30 or 22-10-2017 18:05:50 IST).
even though the above timezone set is UTC you will get output in Device Timezone Only , if You pass your Content Into Your Date Object.
I think, the better way is use Joda Time instead. It's has a ZZ attribute in format, which gives you what you want.
Usage is easy:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZZ").withLocale(Locale.RU);
Related
This question already has answers here:
Parsing ISO-8601 DateTime with offset with colon in Java
(4 answers)
Closed 3 years ago.
I have a date value: - 2019-09-30T00:00:00.000+05:30
I want to convert into the format - dd MMM yyyy
I have the code:
public static String parseDateAndTimeStringCust(String datestring) {
if(datestring.length()>=10){
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String fDate = new SimpleDateFormat("dd MMM yyyy").format(dateFormat2.parse(datestring));
return fDate;
} catch (ParseException ex) {
ex.printStackTrace();
}
}
return datestring;
}
Analysis:
My dateFormat2 I am using is wrong
Question:
What is the correct data format i have to use so that I can get the
result in the format dd MMM yyyy
What is the proper reference I can use in future to build such date
formats
You should use classes from the java.time package.
This is what you're looking for.
String str = "2019-09-30T00:00:00.000+05:30";
OffsetDateTime dt = OffsetDateTime.parse(str);
String out = dt.format(DateTimeFormatter.ofPattern("dd MMM yyyy"));
System.out.println(out);
Note that the actual output depends on your locale, but then you could supply the Locale as the second argument to DateTimeFormatter.ofPattern.
Also note that the single-argument version of OffsetDateTime.parse implies the ISO_OFFSET_DATE_TIME format.
Furthermore, whether the actual output of abovementioned method is accurate, depends on how you want to handle the timezone offset, i.e. whether you want to convert it to UTC or ignore it. For instance, the timestamp 2019-09-30T00:00:00.000+05:30 actually falls on the 29th of September if converted to UTC (the time is then 2019-09-29T18:30:00.000Z).
DateTimeFormatter
The documentation of the DateTimeFormatter class contains detailed information about the formatting symbols and how they are parsed. There are many predefined formats for well-known and commonly used patterns, for example ISO_OFFSET_DATE_TIME conforming with the ISO 8601 standard.
public static String parseDateAndTimeStringCust(String datestring) {
Date dataFormated = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
dataFormated = dateFormat.parse(datestring);
} catch (ParseException ex) {
ex.printStackTrace();
}
return dataFormated.toString();
}
Try changing following line:
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
To:
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
I don't know what I'm doing wrong here. I've got a timestamp (long), and am trying to change it to a readable format.
Here's the timestamp:
1404162530517
When I verify the time using epoch converter, it says it is 5:08PM (correct)
When I try and use my code to parse it, it says 10:21PM (wrong)
Here's the code that doesn't work:
long unixSeconds = Long.parseLong(tstamp);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd", Locale.ENGLISH);
formattedDate = dateFormat.format(date);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"hh:mma ", Locale.ENGLISH);
timeDate = timeFormat.format(date);
System.out.println(tstamp);
System.out.println(timeDate);
How can I fix this?
Okay, so your in the timezone EDT. However, the Unix timestamp is counted from the Unix epoch in UTC. In other words, you are 5 hours behind UTC, and so the timestamp is 5 hours off since it's counting from midnight 1970 in UTC.
So how do you fix this? In your first SimpleDateFormat, put that the input timezone is UTC. That should convert UTC to your time (EDT):
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
formattedDate = dateFormat.format(date);
Have you tried dividing your timestamp by 1000? by default the correct timestamp is only 10 digits I guess.
I just printed new Date() in my box, and it always returns the older time which corresponds to EST, however the date command in the box returns the exact time after moving to EDT, IS there anything that need to be done for the new Date() to return the exact date ? I do not want any alternate java commands, but want the Date to work as it is expected, Am I missing something ?
Thank you
try this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone.
Hi the below code would be useful for your case.
SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy HH:mm:ss z"); //Date format
df.setTimeZone(TimeZone.getTimeZone("EDT")); //set Timezone
df.format(new Date());
Thanks.
This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 9 years ago.
I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);
gives the same date.
Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.
As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");
Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);
See the javadoc of SimpleDateFormat here. Hope that helps.
One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
// Initialize with format of input
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
// Configure the TZ on the date formatter. Not sure why it doesn't get set
// automatically when parsing the date since the input includes the TZ name,
// but it doesn't. One of many reasons to use Joda instead
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(inputDate);
// re-initialize the pattern with format of desired output. Alternatively,
// you could use a new SimpleDateFormat instance as long as you set the TZ
// correctly
sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));
If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy
I am having following function
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
I am using this as follows in my code
Calendar eDate = Calendar.getInstance();
eDate.add(Calendar.DAY_OF_MONTH,10);
Date date = null;
try {
date = parseDate(eDate.getTime().toString(),"yyyy-MM-dd hh-mm-ss");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it is throwing -
java.text.ParseException: Unparseable date
What is the problem here?
The format is not stored in the Date. It is stored in the String. The Date#toString() returns a fixed format which is described in its Javadoc.
Do the formatting only at the moment you need to display a Date to a human as a String.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 10);
Date date = calendar.getTime();
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(formattedDate);
Note that MM stands for months and mm for minutes. See also SimpleDateFormat javadoc.
You'll be happy to hear that there's never a need to parse a date from a Calendar object: The way to pull a Date out of a Calendar is via the getTime() method.
EDIT:
To output the date in eDate in ISO style format:
final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String formattedDate = isoFormat.format(eDate.getTime());
That's untested, but I think it should work.
You're currently formatting with the default format from java.util.Date, and then parsing with a potentially different format. You should also change your format string - it's currently using a 12 hour clock with no am/pm indicator, and minutes twice. I think you mean: "yyyy-MM-dd HH-mm-ss"
Don't use toString() for anything like that. toString() should be used only for debug messages.
Use DateFormat.format(..) to produce a string in a predictable form.
You're inserting a Zulu Timestamp (UNIX), getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. Then you define the format as yyyy-mm-dd hh-mm-ss and try to parse the timestamp with this pattern. Which doesn't match.
You could use Date date = calendar.getTime(); and then format it via new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date);
you can simply use the date returned by the calendar, instead of transforming it into string and back into a date (apparently using a wrong date format). The date can be obtained by:
eDate.getTime()
There seems to be no need for SimpleDateFormat in your case.
Check the Date.toString() method.
The api states that it returns it in
the format:
dow mon dd hh:mm:ss zzz yyyy
which is:
Mon Jan 28 14:22:07 EST 2004
You are telling the parser to expect: 2004-01-28 14-22-07
eDate.getTime().toString()
returns a String representation of a date in this format:
dow mon dd hh:mm:ss zzz yyyy (see the java.util.Date API).
You are trying to parse a date using this format:
yyyy-mm-dd hh-mm-ss .
The code is correctly throwing the ParseException.