I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
Date today = new Date();
today = myFormat.format(today);
I can't do this, because today is a Date, and format returns a String. I also have tried:
Date today;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
try{
today = myFormat.parse((new Date()).toString());
}catch(Exception e){
}
This isn't a good solution, because when I try to use today elsewhere Java complains that today may not have been instantiated. What is a good way to change the format of a Date object (while still keeping it a Date object, and not turning it to a string)?
You are looking at Format and Date wrongly.
Date does not contain format. Date is just a class containing date info like date, month, hours, sec etc.
SimpleDateFormat is the one which tells you the string representation of Date. But there is no date associated with it.
So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.
One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.
Edit:
Now if you want to strip some info from the date. Use
Calendar rightNow = Calendar.getInstance();
Calendar cal = new GregorianCalendar(
rightNow.get(YEAR),
rightNow.get(MONTH),
rightNow.get(DAY_OF_MONTH));
Date now = cal.getTime();
There are other good soln like JodaTime
Ref:
GregorianCalendar
Calendar
Joda Time
I think what you are trying to achieve does not make sense.
A Date object represents time. You can not format it. But, you can get it's string representation in certain format. Like with myFormat.format(today).
I think you're misunderstanding something here about what the Date object is. Date simply holds the information about a point in time - it doesn't have a format at all. When it comes to the String representation of a Date, this is where formatting comes into play. Only worry about the formatting when you are:
Parsing a String representation into a Date object.
Converting a Date back into String representation to display it in a certain way.
Your question doesn't make sense. Formatting a date by definition means converting it to a string using a specific format. The Date object can stay as a Date object. It is only at the point where you wish to convert it to a String that you need to do any formatting.
you cannot associate a format to a Date object instead you can only apply the formats while displaying or other activities,,
Do all processing in the Date object itself and while displaying alone change to the required format,,
Related
I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();
I want format a date given in the following format 1st March 1990. The date should be formatted to YYYY-MM-DD. I have the following code. It gives me an unparsable date. From this i can understand, this is not the correct way to format this date as its not a valid pattern.
public class DateFormattingTest {
public static void main(String[] args) throws ParseException {
String dateString = "1st March 1984";
dateString = dateString.replaceFirst("[a-zA-Z]{2}","") ;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMMM yyyy");
Date rightNow = simpleDateFormat.parse(dateString);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(rightNow);
System.out.println(formattedDate);
}
}
I have revised and looked for date formatting patterns as well. I cannot find something related to this pattern "1st March 1990". I don't want sample code for this issue. I want to find out what am i doing wrong in here? Can someone suggest an approach to parse such a date?
Thanks.
You have three problems.
First, you're trying to parse the date using the format YYYY-MM-DD. That's not the format of your data, which is why parsing is failing.
Second, you're expecting a Date object to retain information about a particular format. It doesn't. Instead, you would parse from one text format to a Date, and then use another DateFormat (with the desired output format) to format the Date into a String. Date.toString() will always use the same format, regardless of how you arrived at the Date.
Third, your format of YYYY-MM-DD isn't really what you want - you want yyyy-MM-dd. YYYY is the "weekyear", and DD is the "day of year".
I don't know of any SimpleDateFormat approach which would handle the ordinal part of your input string ("1st", "2nd" etc) - you'll probably need to put a bit of work into stripping that out. Once you've got a value such as "1 March 1990" you can parse with a SimpleDateFormat using the pattern d MMMM yyyy. Make sure you set the time zone and the locale appropriately.
Your date 1st was not incorporated into the Java DateFormat. If you can switch to 1 and use the appropriate DateFormat, the parsing of Date will work or else you would need to convert the ordinal number to number by stripping the suffix.
This might be a good related post to peek at.
The problem is that your dateString does not match the pattern specified in your simpleDateFormat format. It is expecting a date in the format YYYY-MM-DD, the meaning of these symbols can be found here.
I am getting date in an date object
Date s = ((java.util.Date) ((Object[]) object)[++i]);
i need to set this format 20130509 06:00
so for this I have choosen ..
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
String s1 = sdf.format(s);
now again my task is to put back in date object that string s1, please advise how to achieve this
Date doesn't have a textual format - or even a time zone or calendar. It's just a number of milliseconds since the unix epoch. There's nothing to set within Date.
You need to differentiate between your fundamental data, and a textual representation of that data - in the same way as the int value 16 is the same as 0x10. I can't think of any time where I've found it appropriate to carry a textual representation of a date around with the date itself. In various places in your program you may well find that you need different representations for the same date - but it's usually the same representation for all dates at that specific part of the program.
As an aside, you should consider using Joda Time instead of java.util.Date - it provides you with a much richer set of types to consider, so you can express what your program is actually dealing with (just a date, just a time, a date/time in a particular time zone etc).
Ideally, you shouldn't try to translate to String format and back again. You should persist the original value and just use the String format for display purpose only.
Otherwise, you can use SimpleDateFormat.parse method.
I recommend using Joda time... how given what you've got you can just do
sdf.parse
#Test
public void testDateStringConversion() throws ParseException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
String s1 = sdf.format(date);
Date date2 = sdf.parse(s1); // seconds won't match
String s2 = sdf.format(date2);
assertEquals(s1, s2);
}
So i have String trDate="20120106"; and want to get Date trDate=2012-01-06 and am trying to use SimpleDateFormat for changing the pattern but first i get to parse the string and then generate date and then try to call format which gives me back string but i need date, any suggestions, here is the code i have:
String trDate="20120106";
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).format(tradeDate);
Date krwTradeDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).parse(krwtrDate);
Here is similar question but it does not answer my question
I need converted string in Date format only because i need to pass it to another function that expects Date object only.
Would really appreciate if someone can give example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format?
--- Answer updated due to commentary ---
Ok, so the API you are using demands a String, which represents a Date in the format of 2012-04-20
You then need to parse the incorrectly formatted Date and then format it again in the needed format.
String trDate="20120106";
Date tradeDate = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).format(tradeDate);
Also note that I changed your "month" designator, as you have made a very common mistake of using m for month. Due to the "hours:minutes:seconds" date formats have two common "names" that both start with m, minutes and months. Uppercase M is therefore used for months, while lowercase m is used for minutes. I'll bet that this is the real reason you're encountering problems.
--- Original post follows ---
If your APIneeds a java.util.Date, then you don't need to do as much as you have. You actually have the java.util.Date with just the two lines
String trDate="20120106";
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);
But this solution might not make sense without a quick review of what java.util.Dates are. Dates are things, but how they are presented is divorced from what they are.
At any moment in time, there is one Date instance that describes that moment in time. How that Date instance should be presented is not in agreement, it depends heavily on what language the viewer speaks, which country they are in, what rules the country has imposed (daylight savings time), and what their cultural background has done before.
As such, a Date has no single associated presentation. That's why every "get the X" method on Date is deprecated (where X is day, month, hour, year, etc.), with the exception of grabbing the milliseconds from the 0 date (known as the epoch).
So, for every Date that is to be properly presented, you need to convert it to a String using rules that are specific to the language, country, time zone, and cultural precedent. The object that understands these rules and applies them is the DateFormat.
Which means, once you get the Date you don't need to reformat it and re-parse it to get the "right" Date as the two dates should be the same (for the same locale).
Do I understand it well?
You have a method which only accepts Date as parameter, and internally that method converts the Date to a string in the wrong format using toString()?
Best is to modify that method and exchange the use of toString() with SimpleDateFormat.format().
If you can't modify that method, than you can "cheat" with OO, i. e. replace the toString method with your own implementation, for example like this:
public class MyDate {
private static final FMT = SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
MyDate(long time) {
super(time);
}
String toString() {
return FMT.format(this);
}
}
and you call your method with
xxx = myMethod(new MyDate(new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate).getTime()));
But if that method does not use toString internally but SimpleDateFormat with the wrong format, then my proposition does not work.
can you give me an example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format
A Date objects does not have a format associated with it. Internally it typically just stores a long value.
If some other methods is responsible for printing the date, then you unfortunately have no control over how the resulting output is formatted.
If the String date always comes in the format you have mentioned than you can use the subString method to extract the year, month and day.
String trDate="20120106";
Using the subString method for String extract the Year, month and day
String year = "2012";
String month = "01";
String day = "06";
And parse these to integer. Assuming you will do the parsing of string to integer
int intYear = 2012;
int intMonth = 01;
int intDay = 06;
Calendar calendar= new GregorianCalendar(intYear, intMonth - 1, intDay);
Date date = new Date(calendar);
I have a string obtained by calling the toString method of an instance of the class Date. How can I get a Date object from this string?
Date d = new Date();
String s = d.toString;
Date theSameDate = ...
UPDATE
I've tried to use SimpleDateFormat, but I get java.text.ParseException: Unparseable date
What is the date format produced by Date.toString ()?
If your real goal is to serialize a Date object for some kind of custom made persistence or data transfer, a simple solution would be:
Date d = new Date();
long l = d.getTime();
Date theSameDate = new Date(l);
You could do it like this
Date d = new Date();
String s = d.toString;
Date theSameDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(s);
If your real goal is to serialize and deserialize a date and time (for data transfer or for persistence, for example), serialize to ISO 8601, the standard format for date and time data.
Skip the long outdated Date class. The modern Java date and time API known as java.time is so much nicer to work with. The class you need from it is probably Instant (this depends on your more exact requirements).
The two points go nicely hand in hand:
Instant i = Instant.now();
String s = i.toString();
Instant theSameInstant = Instant.parse(s);
The modern classes’ toString methods produce ISO 8601 format (e.g., 2018-01-11T10:59:45.036Z), and their parse methods read the same format back. So this snippet is all you need, and you get an instant equal to the first, with nanosecond precision.
If you cannot control the string you get, and you get the result from Date.toString(), the format pattern string in Sedalb’s answer works with java.time too:
DateTimeFormatter dtf
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
Date d = new Date();
String s = d.toString();
Instant nearlyTheSameInstant = ZonedDateTime.parse(s, dtf).toInstant();
It’s essential to provide a locale. Otherwise the JVM’s default locale will be used, and if it’s not English, parsing will fail. In the worst case you will see your code running fine for many years and suddenly it will break when one day someone runs it on a computer or device with a different locale setting.
The point from jambjo’s answer still applies: The three and four letter time zone abbreviations used in Date.toString() are very often ambiguous, so there is no guarantee that the time zone is interpreted correctly, and again, it will be interpreted differently on different JVMs.
Finally, Date.toString() does not render the milliseconds that the Date holds, which leads to an inaccuracy of up to 999 milliseconds. If using the string from Date.toString(), there is nothing we can do about it (which was why I named the variable nearlyTheSameInstant).
Take a look at SimpleDateFormat#parse(). It should provide the functionality you're looking for.
Date theSameDate = new Date(Date.parse(s));
For some not so obvious reasons, this is not a particularly good idea. You can find details on that in the API documentation for the parse method. One problem is e.g. that the time zone abbreviations are ambiguous, so that the parser may fail in interpreting the correct time zone.