I am trying to retrieve the current date in the following format: 21-FEB-17.
I have the following code but it isn't the format I need. It prints out in the following format: 21-February-17.
Format formatter = new SimpleDateFormat("dd-MMMM-yy");
String today = formatter.format(new Date());
System.out.println(today);
To get the "first 3 letters" of the month, you should use
Format formatter = new SimpleDateFormat("dd-MMM-yy");
as per the Oracle documentation of SimpleDateFormat.
That will print the month in "Camel" case (i.e., "Feb"). If you want it in all uppercase, you need to do
System.out.println(today.toUpperCase());
Your format had and extra M:
Format formatter = new SimpleDateFormat("dd-MMM-yy");
String today = formatter.format(new Date());
System.out.println(today.toUpperCase());
Here is the link to help you understand better.
And to answer your question use below code.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
String today = formatter.format(new Date());
System.out.println(today.toUpperCase());
This is not the answer you asked for, but it may be the answer you want. :-) As Bojan Petkovic has already said in a comment, if there’s any way you can use Java 8, you will want to use the new java.time classes:
final Locale myLocale = Locale.US;
String today = LocalDate.now()
.format(DateTimeFormatter.ofPattern("d-MMM-yy", myLocale))
.toUpperCase(myLocale);
System.out.println(today);
This prints:
22-FEB-17
You will notice I explicitly use a locale object both for the formatter and for converting to uppercase. You know best which locale you want to use. You may also leave out the locale argument in both places, then the computer’s default locale will be used (so you will get different results on different computers). For a locale neutral formatting, use Locale.ROOT (it will be rather like Locale.US).
Related
So the goal is to be able to get the current date (no problem there) and compare it to a date coming in, which can be either the current date or a date in the future. Not only that, but because of how other languages write out or structure dates, the date string that comes in can change format-wise depending on the language.
If the device is set to English, the string comes in like so:
"Monday, January 30, 2023"
But if the device is set to French, the string looks like this instead:
"lundi 30 janvier 2023"
... and Spanish like this:
"lunes, 30 de enero de 2023"
... and so on. Italian is slightly different, and I've also tried German, which is also slightly different.
I did try DateFormat with DateFormat.LONG and Locale.getDefault() as the parameters (so that it would always use the Locale the device is set to and will always get the full date) but it throws an "unparsable date" error for every language, even the English string.
How would I take any of the given strings above and format them in a way that I can compare the date to the current date (a value like LocalDate.now())? Is there an overarching way to do so across languages, or do I need to create formats for all of these? The purpose is to see how far out the date asked for is from the current date to adjust what is visible in my app (done based on days - is the asked for date 3 days out from the current date? 4 days? 5?).
Thanks in advance for any and all help and insight!
You must to configure your dates patterns for each language (Locale) => This output is exactly what you want, try to adapt it with your function need :
public static void main(String[] args) {
Locale enLocale = Locale.UK;
String datePatternForEn = "EEEE', 'MMMM', 'dd yyyy";
Locale frLocale = Locale.FRANCE;
String datePatternForFr = "EEEE dd MMMM yyyy";
Locale spLocale = new Locale("es", "ES");
String datePatternForSp = "EEEE',' dd' de 'MMMM' de 'yyyy";
DateTimeFormatter englishDateFormat = DateTimeFormatter.ofPattern(datePatternForEn, enLocale);
DateTimeFormatter frenchDateFormat = DateTimeFormatter.ofPattern(datePatternForFr, frLocale);
DateTimeFormatter spanishDateFormat = DateTimeFormatter.ofPattern(datePatternForSp, spLocale);
System.out.println(LocalDate.now().format(englishDateFormat));
System.out.println(LocalDate.now().format(frenchDateFormat));
System.out.println(LocalDate.now().format(spanishDateFormat));
}
I'm trying to turn a String into LocalDate using this code:
String end = sharedPref.getString("endDate", "Not available");
DateTimeFormatter formatter = new DateTimeFormatter("yyyy-MM-dd");
LocalDate endDate = LocalDate.parse(end, formatter);
But it shows the error mentioned in the title. How do I fix it?
If there's a better way I'm open to suggestions
There are no constructor which took a format String, instead you have to call the static method ofPattern like so :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
You don't need an explicit formatter at all in your case.
LocalDate endDate = LocalDate.parse(end);
Just drop the declaration of formatter. The format that you are trying to parse agrees with ISO 8601. LocalDate parses this format as its default, that is, without the formatter.
For the explanation of what went wrong, see the answer by YCF_L.
Link: ISO 8601.
SimpleDateFormat df = new SimpleDateFormat();
Date lastLogin = null;
try {
String troubleChild = lineScanner.next();
lastLogin = df.parse(troubleChild);
} catch (ParseException e) {
System.out.println("ohnoes");
}
Hi I'm quite new to using the date functions and I've come up with a problem. I have a file that is being parsed into various variables and they all work except this one i can never get it so that it passes the try/catch clause i've looked up similar problems but none of them work on my code.(The date i am inputting is in the format: Mon, Oct 30 22:20:11 GMT 2017) please can I get some help and thanks for it!
Solution: java.time
Please don’t take the trouble with the long outmoded classes Date and SimpleDateFormat. Instead use java.time, the modern Java date and time API also known as JSR-310:
DateTimeFormatter dtf
= DateTimeFormatter.ofPattern("E, MMM d H:mm:ss z uuuu", Locale.UK);
String inputDate = "Mon, Oct 30 22:20:11 GMT 2017";
ZonedDateTime lastLogin = ZonedDateTime.parse(inputDate, dtf);
System.out.println(lastLogin);
This prints
2017-10-30T22:20:11Z[GMT]
Since dates and times may come in so many different textual formats, I am using a format pattern string to specify your particular format. For which letters you may use, and what difference it makes whether you use 1, 3 or 4 of the same letter, see the documentation. Beware that format pattern strings are case sensitive.
Problem: SimpleDateFormat
You used the no-arg SimpleDateFormat constructor. The way I read the documentation, this gives you the default date format for your locale. If your JVM is running UK locale, I believe the format goes like 28/11/17 10:57 — not much like the input format you were trying to parse. You can use System.out.println(df.format(new Date())); to find out. The usual SimpleDateFormat constructor to use would be SimpleDateFormat(String, Locale) so that you may again supply a format pattern string and a locale.
This question already has answers here:
Android convert UTC Date to local timezone [duplicate]
(2 answers)
Closed 5 years ago.
I have a date String like 2017-09-16T05:06:18.157 and I want to convert it to local time (IST). In Indian Standard Time it will be around 2017-09-16 10:36:18.
With Joda-Time, I have tried to convert it to local but I was not able to do it.
Below is my code:
private String getConvertDate(String date_server) {
DateTimeFormatter inputFormatter = DateTimeFormat
.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
.withLocale(Locale.US);
DateTime parsed = inputFormatter.parseDateTime(date_server);
DateTimeFormatter outputFormatter = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss")
.withLocale(Locale.US)
.withZone(DateTimeZone.getDefault());
return outputFormatter.print(parsed);
}
Good you found a solution with SimpleDateFormat. I'd just like to add more insights about it (basically because the old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs).
The input String (2017-09-16T05:06:18.157) contains only the date (year/month/day) and time (hour/minute/second/millisecond), but no timezone information. So, when calling parseDateTime, Joda-Time just assumes that it's in the JVM default timezone.
If you know that the input is in UTC, but the input itself has no information about it, you must tell it. One way is to set in the formatter:
// set the formatter to UTC
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
.withZone(DateTimeZone.UTC);
// DateTime will be in UTC
DateTime parsed = inputFormatter.parseDateTime("2017-09-16T05:06:18.157");
Another alternative is to first parse the input to a org.joda.time.LocalDateTime (a class that represents a date and time without a timezone), and then convert it to a DateTime in UTC:
// parse to LocalDateTime
DateTime = parsed = LocalDateTime.parse("2017-09-16T05:06:18.157")
// convert to a DateTime in UTC
.toDateTime(DateTimeZone.UTC);
Both produces the same DateTime, corresponding to UTC 2017-09-16T05:06:18.157Z.
To format it to "IST timezone" (which is actually not a timezone - more on that below), you can also set the timezone in the formatter:
// convert to Asia/Kolkata
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
.withZone(DateTimeZone.forID("Asia/Kolkata"));
System.out.println(outputFormatter.print(parsed));
Or you can convert the DateTime to another timezone, using the withZone() method:
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
// convert to Asia/Kolkata
System.out.println(outputFormatter.print(parsed.withZone(DateTimeZone.forID("Asia/Kolkata"))));
Both will print:
2017-09-16 10:36:18
In your code you're using DateTimeZone.getDefault(), that gets the JVM default timezone (with some tricky details). But the default timezone can be changed without notice, even at runtime, so it's always better to specify which one you want to use.
Also, keep in mind that short names like IST are not real timezones. Always prefer to use IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard. Just check in this list that IST can be "India Standard Time", "Israel Standard Time" and "Irish Standard Time".
You can get a list of available timezones (and choose the one that fits best your system) by calling DateTimeZone.getAvailableIDs().
Java new Date/Time API
Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".
If you can't (or don't want to) migrate from Joda-Time to the new API, you can ignore this section.
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.
First, you can parse the input to a org.threeten.bp.LocalDateTime, then I use a org.threeten.bp.ZoneOffset to convert it to UTC, resulting in a org.threeten.bp.OffsetDateTime.
Then, I use a org.threeten.bp.ZoneId to convert this to another timezone, and use a org.threeten.bp.format.DateTimeFormatter to format it (this is basically what's suggested by #Ole V.V's comment - just to show how straightforward it is, as there aren't anything much different to do):
// parse to LocalDateTime
OffsetDateTime parsed = LocalDateTime.parse("2017-09-16T05:06:18.157")
// convert to UTC
.atOffset(ZoneOffset.UTC);
// convert to Asia/Kolkata
ZoneId zone = ZoneId.of("Asia/Kolkata");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(outputFormatter.format(parsed.atZoneSameInstant(zone)));
The output is:
2017-09-16 10:36:18
try this code:
String serverdateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public String convertServerDateToUserTimeZone(String serverDate) {
String ourdate;
try {
SimpleDateFormat formatter = new SimpleDateFormat(serverdateFormat, Locale.UK);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(serverDate);
TimeZone timeZone = TimeZone.getTimeZone("Asia/Kolkata");
SimpleDateFormat dateFormatter = new SimpleDateFormat(serverdateFormat, Locale.UK); //this format changeable
dateFormatter.setTimeZone(timeZone);
ourdate = dateFormatter.format(value);
//Log.d("OurDate", OurDate);
} catch (Exception e) {
ourdate = "0000-00-00 00:00:00";
}
return ourdate;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utcZone = TimeZone.getTimeZone("UTC");
simpleDateFormat.setTimeZone(utcZone);
Date myDate =simpleDateFormat.parse(rawQuestion.getString("Asia/Kolkata"));
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(myDate);
I want to get the current DateTime in a zone of my choice and in a particular format (eg HH-MM-SS, MM-DD-YY, MoMo-DD-YY-HH-MM-SS etc).
How can I do this, using JodaTime?
Given that you've already seen the user guide (which includes sections on time zones and formatting), it's not really clear where your confusion is. Some sample code to get you going:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime currentTimeInLondon = new DateTime(zone);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss, MM-dd-yyyy");
String text = formatter.print(currentTimeInLondon); // e.g. 08:24:54, 09-26-2012
It would be worth you taking some time to analyze why you couldn't get to this code yourself, given the information in the user guide. Being able to work out how to use APIs is a very important skill as a software engineer - you mustn't expect to be spoonfed code all the time.
this may help you.
http://joda-time.sourceforge.net/userguide.html
Use following code to get time according to particular zone with format.
Locale locale = Locale.FRENCH;
// Format with a custom format
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
String s = formatter.format(new Date());
// mar., 29 sept. 2012
// Format with a default format
s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
// 29 sept. 2012