I have a String with several dates:
[20-Jul-2012 5:11:36,670 UTC PM, 20-Jul-2012 5:11:36,683 UTC PM]
ParsePosition parsePos = new ParsePosition(1);
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a");
System.out.println(format2.parse(entry.getValue().toString(), parsePos)) ;
Output : Fri Jul 20 06:11:36 BST 2012
I need the output to be 20-Jul-2012 5:11:36,670 UTC PM.
Do I need to set a LOCALE in the SimpleDateFormat to not have a different output?
You need to set the time zone, but more importantly, you simply need to actually use the format to format the date:
Date date = format2.parse(...);
String formattedDate = format2.format(date);
System.out.println(formattedDate);
What your code does is:
Date date = format2.parse(...);
System.out.println(date.toString());
I don't really understand the point in parsing a string to a date, and then displaying the date using the exact same format, though (except to validate that the String is indeed a valid date, but then you could simply reuse the original string).
You've got two small problems:
Use hh for the hour, not HH. H is "Hour in day (0-23), and so will not work correctly with a, the AM/PM marker. Your two example date strings will parse to AM, not PM.
You're using SimpleDateFormat to parse the string, but not format it. Use format2.format(format2.parse(entry.getValue().toString()).
Here's a complete example:
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss,SSS z a");
String input = "20-Jul-2012 5:11:36,670 UTC PM";
Date date = format.parse(input);
String output = format.format(date);
System.out.println(output);
Result:
20-Jul-2012 05:11:36,670 UTC PM
Related
I have a DateTime in the format of Tue, 30 Apr 2019 16:00:00 +0800 which is RFC 2822 formatted date
I need to convert this to the given timezone in the DateTime which is +0800
So if i summarized,
DateGiven = Tue, 30 Apr 2019 16:00:00 +0800
DateWanted = 01-05-2019 00:00:00
How can i achieve this in Java?
I have tried the below code but it gives 08 hours lesser than the current time which is
30-04-2019 08:00:00
Code i tried
String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date startDate = format.parse(programmeDetails.get("startdate").toString());
//Local time zone
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
//Time in GMT
Date dttt= dateFormatLocal.parse( dateFormatGmt.format(startDate) );
You are on right approach but just use java-8 date time API module, first create DateTimeFormatter with the input format representation
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z");
And then use OffsetDateTime to parse string with offset
OffsetDateTime dateTime = OffsetDateTime.parse("Tue, 30 Apr 2019 16:00:00 +0800",formatter);
And the call the toLocalDateTime() method to get the local time
LocalDateTime localDateTime = dateTime.toLocalDateTime(); //2019-04-30T16:00
If you want the output in particular format again you can use DateTimeFormatter
localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) //2019-04-30T16:00:00
Note : As #Ole V.V pointed in comment, after parsing the input string into util.Date you are getting the UTC time
The class Date represents a specific instant in time, with millisecond precision.
So now if you convert the parsed date time into UTC you get 2019-04-30T08:00Z without offset, so you can use withOffsetSameInstant to convert it into any particular timezone
dateTime.withOffsetSameInstant(ZoneOffset.UTC)
You misunderstood. According to RFC 2822 +0800 means that an offset of 8 hours 0 minutes has already been applied to the time compared to UTC. So the output you got was the correct GMT time.
java.time
I recommend you skip the old and outdated classes SimpleDateFOrmat and Date. It’s much nicer to work with java.time, the modern Java date and time API. Furthermore it has the RFC format built in, so we don’t need to write our own formatter.
OffsetDateTime parsedDateTime = OffsetDateTime
.parse("Tue, 30 Apr 2019 16:00:00 +0800",
DateTimeFormatter.RFC_1123_DATE_TIME);
ZonedDateTime dateTimeInSingapore
= parsedDateTime.atZoneSameInstant(ZoneId.of("Asia/Singapore"));
System.out.println("In Singapore: " + dateTimeInSingapore);
OffsetDateTime dateTimeInGmt
= parsedDateTime.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("In GMT: " + dateTimeInGmt);
Output:
In Singapore: 2019-04-30T16:00+08:00[Asia/Singapore]
In GMT: 2019-04-30T08:00Z
The built-in formatter is named RFC_1123_DATE_TIME because the same format is used in multiple Requests for Comments (RFCs).
Links
RFC 2822 Internet Message Format
Oracle tutorial: Date Time explaining how to use java.time.
with the help of #ole v.v's explanation i have separated the datetime value for two
1. time
2. timezone
then i used this coding to extract the datetime which is related to the given timezone
//convert datetime to give timezone
private static String DateTimeConverter (String timeVal, String timeZone)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(timeZone));
String result =null;
try {
result = offsetDateFormat2.format(format.parse(timeVal));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
I have a database file with mm/dd/yy values for events, and I want to display the date as something similar to "Day(word), day(number), month(word)".
01/07/19 into
Monday 4th Jan or Monday 4 Jan or something similar.
Try something like this:
LocalDate.of(2019, 3, 2).format(DateTimeFormatter.ofPattern("EEE dd MMM YYYY"))
You can use SimpleDateFormat to convert the string to date and then convert back to String like this :
DateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
Date date = format1.parse("01-01-2019");
DateFormat format2 = new SimpleDateFormat("MMMMM dd, yyyy");
String dateString = format2.format(date);
System.out.println(dateString); //<- prints January 01, 2019
How to use the SimpleDateFormat?
Java provides a class called a SimpleDateFormat that allows you to format and parse dates in the as per your requirements.
You can use the above characters to specify the format - For example:
1) Date format required: 2019.01.01 20:20:45 PST
The appropriate date format specified will be- yyyy.MM.dd HH:mm:ss zzz
2) Date format required:09:30:00 AM 01-Jan-2019
The appropriate date format specified will be-hh:mm:ss a dd-MMM-yyyy
Tip: Be careful with the letter capitalization. If you mistake M with m, you will undesired results!
Let's learn this with a code example.
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDates_Format {
public static void main(String args[]) {
Date objDate = new Date(); // Current System Date and time is assigned to objDate
System.out.println(objDate);
String strDateFormat = "hh:mm:ss a dd-MMM-yyyy"; //Date format is Specified
SimpleDateFormat objSDF = new SimpleDateFormat(strDateFormat); //Date format string is passed as an argument to the Date format object
System.out.println(objSDF.format(objDate)); //Date formatting is applied to the current date
}
}
Output :
Sat Mar 02 16:37:59 UTC 2019
04:37:59 PM 02-Mar-2019
Have a nice day !
I am trying to convert UTC Date to IST. But to my surprise, after converting everything, it is still returning me UTC only. How is it possible?
INPUT:
StartDateTimeUtc='2017-09-15T14:00:00',
EndDateTimeUtc='2017-09-15T15:00:00'
Code:
public static final String DATE_FORMATE_CURRENT = "yyyy-MM-dd'T'HH:mm:ss";
Date meetingStartDate = new SimpleDateFormat(Constants.DATE_FORMATE_CURRENT, Locale.ENGLISH).parse(model.StartDateTimeUtc);
Date meetingEndDate = new SimpleDateFormat(Constants.DATE_FORMATE_CURRENT, Locale.ENGLISH).parse(model.EndDateTimeUtc);
//Convert Date to String
DateFormat df = new SimpleDateFormat(Constants.DATE_FORMATE_CURRENT);
String meetinStartDateString = df.format(meetingStartDate);
String meetingEndDateString = df.format(meetingEndDate);
//Convert String Date to IST
SimpleDateFormat dftwo = new SimpleDateFormat(Constants.DATE_FORMATE_CURRENT);
dftwo.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
Date date = null;
Date datetwo = null;
try {
date = dftwo.parse(meetinStartDateString);
datetwo = dftwo.parse(meetingEndDateString);
} catch (ParseException e) {
e.printStackTrace();
}
dftwo.setTimeZone(TimeZone.getDefault());
String formattedStartDate = dftwo.format(date);
String formattedEndDate = dftwo.format(datetwo);
//Convert String Date back to Date format so that we can pass into Calendar code
Date meetingStartDateFinal = new SimpleDateFormat(Constants.DATE_FORMATE_CURRENT, Locale.ENGLISH).parse(formattedStartDate);
Date meetingEndDateFinal = new SimpleDateFormat(Constants.DATE_FORMATE_CURRENT, Locale.ENGLISH).parse(formattedEndDate);
OUTPUT again in UTC:
Start Date : Fri Sep 15 14:00:00 GMT+05:30 2017
End Date : Fri Sep 15 15:00:00 GMT+05:30 2017
A java.util.Date doesn't have any timezone information. It just contains one value: the number of milliseconds since unix epoch (1970-01-01T00:00Z, or January 1st 1907, at midnight in UTC).
This number of milliseconds is the same, everywhere in the world. What's is different is the corresponding date and time in each timezone. Example: right now, this millis value is 1505481835424, which corresponds, in UTC, to 2017-09-15T13:23:55.424Z. This same value corresponds to 10:23 AM in São Paulo, 18:53 in Kolkata, 14:23 in London and so on. The local date/time is different in each timezone, but the millis value is the same for everyone.
That's why you don't convert a Date itself: the millis value is the same, and there's no need to change it. What you can change is the representation of this date in different timezones.
SimpleDateFormat, by default, uses the JVM default timezone to parse dates. But if you know that the inputs are in a specific zone, you must set in the formatter. So, to parse your inputs, you must do:
String startDateTimeUtc = "2017-09-15T14:00:00";
String endDateTimeUtc = "2017-09-15T15:00:00";
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss");
// input is in UTC
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// parse dates
Date meetingStartDate = sdf.parse(startDateTimeUtc);
Date meetingEndDate = sdf.parse(endDateTimeUtc);
The 2 Date objects above will correspond to 14:00 and 15:00 UTC (which is the same as 19:30 and 20:30 in Kolkata timezone).
But if you just print the Date objects directly (using System.out.println, logging, or even checking their values in a debugger), it'll implicity call the toString() method, which uses the JVM default timezone behind the scenes, resulting in the output you're seeing (Fri Sep 15 14:00:00 GMT+05:30 2017).
If you want to print in a specific format, and in a specific timezone, you'll need another formatter:
// another formatter for output
SimpleDateFormat outputFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// output will be in Asia/Kolkata timezone
outputFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println(outputFormat.format(meetingStartDate));
System.out.println(outputFormat.format(meetingEndDate));
The output will be:
2017-09-15T19:30:00
2017-09-15T20:30:00
Which corresponds to the same UTC dates in Kolkata timezone.
Just remember: you don't convert the Date's between timezones (because their millis values are "absolute" - they are the same for everyone in the world). You just change the String representation of those dates (the corresponding date/time in a specific timezone).
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.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
This new API has lots of different date/time types for each situation. In this case, the inputs have date and time, but no timezone information, so first I parse them to a org.threeten.bp.LocalDateTime, using a org.threeten.bp.format.DateTimeFormatter:
// parse the inputs
DateTimeFormatter fmt = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime startDt = LocalDateTime.parse(startDateTimeUtc, fmt);
LocalDateTime endDt = LocalDateTime.parse(endDateTimeUtc, fmt);
Then I use a org.threeten.bp.ZoneOffset to convert them to UTC, and later a org.threeten.bp.ZoneId to convert this to another timezone. The result will be a org.threeten.bp.ZonedDateTime:
// input is in UTC
ZoneOffset utc = ZoneOffset.UTC;
// convert to Asia/Kolkata
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZonedDateTime start = startDt.atOffset(utc).atZoneSameInstant(zone);
ZonedDateTime end = endDt.atOffset(utc).atZoneSameInstant(zone);
Then I use the same DateTimeFormatter to format the output:
System.out.println(fmt.format(start));
System.out.println(fmt.format(end));
The output is:
2017-09-15T19:30:00
2017-09-15T20:30:00
Note that I don't need to set the timezone in the formatter, because the timezone information is in the objects (they are responsible to do the conversion).
I am retrieving date from database. Datatype is'date' with date format 2015-12-16.
I need to set that date to my bean class variable.Datatype is Date with format 16-Dec-2015
These are the date formats i am using
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
String formatteddate = null;
try {
formatteddate = formatter.format(rs.getDate("dol"));
System.out.println("formatteddate=============="+formatteddate);
date = formatter.parse(formatteddate);
System.out.println("date========="+date);
} catch (ParseException e) {
e.printStackTrace();
}
joborderbean.setDol(date);
formatteddate==============15-Dec-2015
I want to display the above format i.e,15-Dec-2015. But it is diplaying the below format
date=========Tue Dec 15 00:00:00 IST 2015
Please help me
Do like following:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateformat=fromatter.format(mysqldate);
System.out.println("first date format"+ dateformat);
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
String dateformat1=formatter1.format(mysqldate);
System.out.println("second date format"+dateforamt1);
also you can edit the sql fired to get the result like
select DATE_FORMAT(date_field,'%Y-%b-%d')
and
select DATE_FORMAT(date_field,'%d-%b-%Y')
First of all the Resultset objects getDate method return a java.sql.Date object. So in order to store the Date in the date object use :
date = rs.getDate("dol");
instead of the code:
formatteddate = formatter.format(rs.getDate("dol"));
System.out.println("formatteddate=============="+formatteddate);
date = formatter.parse(formatteddate);
System.out.println("date========="+date);
now in order to test the date you can use:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
System.out.printLn("date========="+formatter.format(date));
This will give you the required output.
The last output you are getting because of the code System.out.println("date========="+date); Here the toString method of the date object is getting called which has a default as in the documentation as :
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
where:
dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
dd is the day of the month (01 through 31), as two decimal digits.
hh is the hour of the day (00 through 23), as two decimal digits.
mm is the minute within the hour (00 through 59), as two decimal digits.
ss is the second within the minute (00 through 61, as two decimal digits.
zzz is the time zone (and may reflect daylight saving time). Standard time zone abbreviations include those recognized by the method parse. If time zone information is not available, then zzz is empty - that is, it consists of no characters at all.
yyyy is the year, as four decimal digits.
How can i get data in format "YYYY-MM-DD 00:00:00.0" using class Date (it's extremly important to use exactly this class)?
I tried to do everything i can think of:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
df.format(date)
and
String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("2011-01-18 00:00:00.0");
} catch (ParseException e) {
e.printStackTrace();
}
byt when i print date using logger i get this format "Tue Sep 30 00:00:00 MSK 1913".
Try this
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date = format.parse("2011-01-18 00:00:00.0");
System.out.println(format.format(date));
Are you sure you want the hours, minutes, secs to be zeroes?
Or do you mean the pattern yyyy-MM-dd HH:mm:ss ?
The date class is always independent of the formatting. It only needs to be translated when you print it, like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String out = df.format(date)
System.out.println(out);
Or do you want to strip the time out of the date object? or something.
You are confused by Date.toString() and SimpleDateFormat.format()
An object of Date (java.util.Date) has no format information. If you call date.toString(), (which is called by your logger), you got default representation of this object, you have seen what it is.
However, SimpleDateFormat.format() will give you a string as return value, this value will format the Date object with a pattern defined by SimpleDateFormat.
In your code, you first parsed the string, with certain pattern, to get the date object. If it was successful, you got the Date object, here, for this date object, you don't have any format information, even if you have defined a pattern to parse the input string. If you want to print/output (to string again) the date object, you have to use the SimpleDateFormat.format() method.
I hope the below one will solve your problem when you need to do for dynamic dates.
Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String formattedDate = sdf.format(today);
System.out.println(formattedDate);
//Above line output (formatted String object) is 2017-12-29 00:00:00
System.out.println(format.format(formattedDate));
//Above line output(parsed Date object) is Fri Dec 29 00:00:00 IST 2017
For Date object you can't get the output as yyyy-MM-dd 00:00:00, but you will get this format in String object type.