I have the following date format I need to parse:
Aug 6, 2013 18:34:16.990423000
So I tried the following:
Date startTime;
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss.S", Locale.ENGLISH);
startTime = df.parse("Aug 6, 2013 18:34:16.990423000");
But then mydate.toString gives me completely other date!
It gives me "Sun Aug 11 11:27:43 IDT 2013"!
Does it relate to time zone?
By the way, when I perform
ts = returnTime.getTime() - startTime.getTime();
it seems to return the correct answer. But I am not sure it is always so.
The problem is with the S which indicates milliseconds. It adds that number of milliseconds to the date but you have 990423000 milliseconds. You might want to leave out the .S of your format or truncate your input first as in the following example:
Date startTime;
String dateString = "Aug 6, 2013 18:34:16.990423000";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy kk:mm:ss.SSS", Locale.ENGLISH);
startTime = df.parse(dateString.replaceFirst("\\.(\\d{3})\\d*$", ".$1"));
System.out.println(new SimpleDateFormat("MMM dd, yyyy kk:mm:ss.SSS").format(startTime));
Related
I am getting the date in long format like this :
Wednesday, August 1, 2018
I want this in the below format:
Wed, Aug 01, 2018
I used the below code:
public static String getShortDate(Date date){
SimpleDateFormat format = new SimpleDateFormat("E, MMM dd, yyyy");
return format.format(date);
}
This works fine for en_US. But how to make it work for other locales
For example the long format for German is :
Samstag, 16. Juni 2018
how to get the above short format for it?
The getShortDate method parameter takes Date, but I can change it to String.
If the longer format is : Samstag, 16. Juni 2018
i need it to be : Sa., 16. Jun. 2018
i am using the below code :
SimpleDateFormat format = new SimpleDateFormat("E, dd MMM, yyyy", locale);
return format.format(date);
This is giving me output as: Sa, 16 Jun, 2018
How to get that dot(.) after Sa
To get short date format in different locale code, you could try below code:
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("E, MMM dd, yyyy", new Locale("de", "de"));//for german germany
String date = simpleDateFormat.format(new Date());
Output:
Di, Mär 27, 2018
Here is my original code-
String dateString = "23 Dec 2015 1:4 PM";
Locale locale = new Locale("en_US");
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
Date date = null;
try {
date = formatter.parse(dateString);
} catch (ParseException e) {
LOGGER.error(e);
}
String newDate = df.format(date);
System.out.println("oldDate = " + dateString);
System.out.println("newDate = " + newDate);
and here is my output-
oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 AM
There is AM-PM difference between the oldDate and newDate. Now I changed the DateFormat code to-
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm a", locale);
and I get the expected output, which is-
oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 PM
I'm aware that HH signifies the 24 hour format and hh signifies the 12-hour format.
My question is
If I use HH:mm a instead of hh:mm a, shouldn't this be returning the time in 24-hour format?
(or)
If it defaults to 12-hour format, shouldn't it return respective AM/PM marker depending on the date input provided?
This is just for my understanding.
Updated Answer
Here the problem is with Program flow
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
this simple date formatter is used to format the date string the Date object is created, here is the important part of answer
As you are using HH instead of hh, the SimpleDateFormater considers that provided date string is in 24-Hour Format and simply ignores the AM/PM marker here.
The Date Object from constructed from this SimpleDateFormatter is passed to the
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
That's why it's printing
newDate = 23 Dec 2015 01:04 AM
if you change the line
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
with
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
Everything will go smooth as it should!
Note : when creating a locale you should pass the language code to the Locale() constructor. en-us not en_us.
IMP : Code is tested on Java 8 also. Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Difference between hh:mm and HH:mm:
HH:mm => will look like 00:12, 23:00... this has 24 hour format.
hh:mm => will look like 01:00Am, 02:00Am,...01:00pm this has 12 hour format.
And the a in hh:mm a or in HH:mm a is Am/pm marker for more info go to link
A simple test is the best answer to how the pattern "HH:mm a" is interpreted. First let us investigate the printing mode:
The old format engine SimpleDateFormat:
Calendar cal = new GregorianCalendar(2015, 3, 1, 17, 45);
SimpleDateFormat sf = new SimpleDateFormat("HH:mm a", Locale.US);
System.out.println(sf.format(cal.getTime())); // 17:45 PM
Java-8 (with the new package java.time.format):
LocalTime time = LocalTime.of(17, 59);
DateTimeFormatter tf = DateTimeFormatter.ofPattern("HH:mm a", Locale.US);
System.out.println(tf.format(time)); // 17:59 PM
Here we don't observe any override in both cases. I prefer that approach because using the combination of "HH" and "a" is in my opinion rather an indication for a programming error (the user has obviously not thought enough about the meaning and official description of those pattern symbols).
Now let us investigate the parsing mode (and we will use strict mode to observe what is really going behind the scene):
String dateString = "23 Dec 2015 1:4 PM";
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy H:m a", Locale.US);
df.setLenient(false);
Date date = df.parse(dateString);
// java.text.ParseException: Unparseable date: "23 Dec 2015 1:4 PM"
How is the behaviour in Java-8? It is the same but with a clearer error message:
DateTimeFormatter tf = DateTimeFormatter.ofPattern("H:m a", Locale.US);
tf = tf.withResolverStyle(ResolverStyle.STRICT);
LocalTime.parse("1:4 PM", tf);
// DateTimeException: Cross check failed: AmPmOfDay 0 vs AmPmOfDay 1
This message tells us that the parsed hour (in 24-hour format!) with value "1" indicates AM while the text input contains the other parsed AM/PM-value "PM". This ambivalence cannot be resolved.
Lesson: We have to be careful with lenient parsing where contradictious information can be ignored and lead to false assumptions. The accepted answer of #Arjun is completely wrong.
By the way: Please use Locale.US or new Locale("en", "US") instead of new Locale("en-US") because the language "en-US" does not exist.
I can't figure out why this is returning
Wed Jul 02 18:21:27 CDT 2014
instead of
07/02/14 6:21 pm
pubdate = Mon, 30 Jun 2014 22:37:15 +0000
public void setPubDate(String pubDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
long x = dateFormat.parse(pubDate).getTime();
Date date = new Date(x);
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
newFormat.format(dateFormat.parse(pubDate));
this.pubDate = date;
}
If you want to print the format you want, you have to use String to represent your date, otherwise, Date type will always print this format "dow mon dd hh:mm:ss zzz yyyy"
this.pubDate = date;//Assign the reference of date Object
//this.pubDate will have value of date NOT Format :)
But here format won't be passed to pubDate as that will remain as it is.
If you want to make your pubDate to have dd/Mm/yyyy aa format you have to format the pubDate as well here you are only assigning reference from one date to other but formation on one date won't affect the other one you have to apply that to this.pubDate whenever you want to use pubDate.
You can declare general format(Class level Object) and use it in your program whenever you want to display the date.
Because Date has toString() which per the Javadoc,
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.
When you want to deviate from that, you will need your newFormat -
// As a String
System.out.println(newFormat.format(dateFormat.parse(pubDate)));
public void setPubDate(String pubDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
long x = dateFormat.parse(pubDate).getTime();
Date date = new Date(x);
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
return newFormat.format(dateFormat.parse(pubDate));
}
Use corrected code below:
public void setPubDate(String pubDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
long x = dateFormat.parse(pubDate).getTime();
Date date = new Date(x);
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
System.out.println("Formatted date is ="+ newFormat.format(x));
}
Try this, Create your custom date class
public class MyDate extends Date
{
#Override
public String toString() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy hh:mm aa");
return dateFormat.format(new Date());
}
}
then print the object like
System.out.println(new MyDate());
I use DateTimeZone.convertLocalToUTC to convert local time to UTC. The time is changed correctly, but after conversion, the timezone info still says the Original local timezone. Please refer below sample code
Date gmttime = new Date(tz.convertLocalToUTC(System.currentTimeMillis(),false));
System.out.println(gmttime.toString());
Output :
Wed Oct 16 12:58:19 IST 2013
Please note the bold value, I expected it to be UTC . Please let me know if I am missing something.
#Date.toString() will print the date in the local timezone.
Use SimpleDateFormat to print the Date formatted for a specific TimeZone:
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("E MMM dd HH:mm:ss:SS z");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.format(date));
}
Try:
final Date date = new Date();
final String ISO_FORMAT = "E MMM dd HH:mm:ss zzz yyyy";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
System.out.println(sdf.format(date));
Output:
Wed Oct 16 08:53:50 UTC 2013
convertLocalToUTC Converts a local instant to a standard UTC instant with the same local time. http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html
Is it possible to remove the day (Fri), the time (22:34:21) and the time zone (GMT) by just having an output like "Jan 11 1980" instead of "Fri Jan 11 22:34:21 GMT 1980"??
Code below:
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, 1980);
date.set(Calendar.MONTH, 0);
date.set(Calendar.DAY_OF_MONTH, 11);
Date dob = date.getTime();
System.out.println(dob);//Fri Jan 11 22:34:21 GMT 1980
Many thanks!
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
System.out.println(sdf.format(date));
Output:
Feb 26 2013
If you want a specific date, do
Calendar c = Calendar.getInstance();
c.set(1980, 0, 11);
Date date = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
System.out.println(sdf.format(date));
Prints
Jan 11 1980
public class DateFormat {
public static void main(String[] args) {
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, 1980);
date.set(Calendar.MONTH, 0);
date.set(Calendar.DAY_OF_MONTH, 11);
Date dob = date.getTime();
System.out.println(new SimpleDateFormat("MMM dd yyyy").format(dob));
}
}
Output:
Jan 11 1980
Date is a representation of the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT)
In order to "remove" the time portion of a Date, you will want to use a DateFormat
Something as simple as;
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(dob));
Should work.
For a more localised version, you should use DateFormat.getDateInstance()
System.out.println(DateFormat.getDateInstance().format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.MEDIUM).format(dob));
System.out.println(DateFormat.getDateInstance(DateFormat.LONG).format(dob));
DateFormat dateFormatter = DateFormat.getDateInstance();
System.out.println(dateFormatter.format(date);
This will print the only the date corresponding to your current system locale settings.
See also: DateFormat in the JavaDoc
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
System.out.println(sdf.format(dob));
you can use:
stringToPrint = time.getMonth()+" "+time.getDate()+" "+time.getYear();
for more info:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html