How to convert mm/dd/yy string to "Monday 7th Jan" - java

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 !

Related

How can i convert String to Date when it has "TRT" in it

String sDate = "06.08.2020" // 06 day 08 month 2020 is year
This is the date i have in my txt file. I use them in JTable. To sort the table i convert them to date with this DateFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
And it does convert the string to date as this.
LocalDate date = LocalDate.parse(sDate,formatter);
//The date : Thu Aug 06 00:00:00 TRT 2020
Now i need to convert it like the first date 06.08.2020.
But i can't use date as input. Because i get it from JTable so i get it as String.
So i tryed this code.
String sDate1 = "Thu Aug 06 00:00:00 TRT 2020";// The date i get from JTable
LocalDate lastdate = LocalDate.parse(sDate1,formatter);
sDate1 = formatter.format(lastdate);
But i get an error as this Text 'Thu Aug 06 00:00:00 TRT 2020' could not be parsed at index 0.
So this cone not works fine : LocalDate lastdate = LocalDate.parse(sDate1,formatter);
I cant see where is the problem.
I cannot reproduce the behaviour you describe. The following code worked fine for me:
import java.util.*;
import java.text.*;
public class MyClass {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = "06.08.2020";
Date date1 = sdf.parse(date);
String result = sdf.format(date1);
System.out.println("Date = " + result);
}
}
Output: Date = 06.08.2020
That being said, if at all possible you should switch to the new java.time.* API.
Where your code failed:
SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);
As you can see, the pattern of the SimpleDateFormat and that of the date string do not match and therefore, this code will throw ParseException.
How to make it work?
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
You must have already got why it worked. It worked because the pattern of the SimpleDateFormat matches with that of the dateStr string.
Can I format the Date object (i.e. date) into the original string?
Yes, just use the same format which you used to parse the original string as shown below:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);
A piece of advice:
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
Using the modern date-time API:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);
I don't see any difference using the legacy API and the modern API:
That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.
Demo:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDate = "Thu Aug 06 00:00:00 TRT 2020";
// Replace TRT with standard time-zone string
strDate = strDate.replace("TRT", "Europe/Istanbul");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
// Parse the date-time string into ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
System.out.println(zdt);
// If you wish, convert ZonedDateTime into LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00

How to convert date from mm/dd/yyyy to mm dd, yyyy

I want to convert date from 07/02/2019 to July 07, 2019. My input value is 07/02/2019 I want to compare with target value July 07, 2019....Please help me on this...
public static void main(String[] args) throws ParseException {
String sDate1="07/01/2019";
java.util.Date date1=new SimpleDateFormat("MM/dd/yyyy").parse(sDate1);
System.out.println(date1);
Output:Mon Jul 01 00:00:00 IST 2019 which is not my expected value
Try this one.
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
SimpleDateFormat output = new SimpleDateFormat("MMMM dd, yyyy");
Date data = sdf.parse("07/02/2019");
String newDate = output.format(data);
System.out.println(newDate);
Here, you use:
java.util.Date date1=new SimpleDateFormat("MM/dd/yyyy").parse(sDate1);
to parse a date that comes in as String.
Then you print that date without any formatting information.
Thus the answer is quite simple: define a pattern for formatting a Date object as string! Same rules, same patterns. Just not parsing, but formatting for printing!
In other words: you already know the concept, you used a formatter to turn a String into a Date. Now simply turn that around, and provide a pattern to a formatter to turn a Date into a string!
Parse your input date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
LocalDate date = LocalDate.parse(sDate, formatter);
Similarly parse your target date
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("MMMM dd, uuuu", Locale.ENGLISH);
LocalDate targetDate = LocalDate.parse("July 07, 2019");
Or better yet, define your target date without using a string
LocalDate targetDate = LocalDate.of(2019, Month.JULY, 7);
Compare
if (date.equals(targetDate)) {
System.out.println("Same date");
}
LocalDate also have methods isBefore and isAfter.
This answer is entered from my tablet without trying the code out, so please forgive the typos.

Format date and time in String format from an API response [duplicate]

This question already has answers here:
Parsing ISO_INSTANT and similar Date Time Strings
(4 answers)
Java / convert ISO-8601 (2010-12-16T13:33:50.513852Z) to Date object
(4 answers)
Closed 5 years ago.
I'm using the Guardian API to get recent news stories about football.
I want to show date and time info to the user, but not in the format the API throws it back to me.
When requesting webPublicationDate after querying http://content.guardianapis.com/search?page-size=10&section=football&show-tags=contributor&api-key=test I get the response in this format:
2017-06-22T16:18:04Z
Now, I want the date and time info in this format:
e.g. Jun 21, 2017 and 16:18 or 4:18 pm.
While I basically know to format a Date object properly into this format:
/**
* Return the formatted date string (i.e. "Mar 3, 1984") from a Date object.
*/
private String formatDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("LLL dd, yyyy");
return dateFormat.format(dateObject);
}
/**
* Return the formatted date string (i.e. "4:30 PM") from a Date object.
*/
private String formatTime(Date dateObject) {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
return timeFormat.format(dateObject);
}
But I can't seem to convert the response I get into a Date object.
You can format the text this way:
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateExample5 {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateInString = "2014-10-05T15:23:01Z";
try {
Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
System.out.println(date);
System.out.println("time zone : " + TimeZone.getDefault().getID());
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Z suffix means UTC, java.util.SimpleDateFormat doesn’t parse it correctly, you need to replace the suffix Z with ‘+0000’.
Code from here: https://www.mkyong.com/java/how-to-convert-string-to-date-java/
Instead of directly working with SimpleDateFormat (as this old API has lots of problems and design issues), you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To use it in Android, you'll also need the ThreeTenABP (more on how to use it here).
The main classes to be used are org.threeten.bp.ZonedDateTime (which can parse the date/time input) and org.threeten.bp.format.DateTimeFormatter (to control the output format).
If you are reading this field (2017-06-22T16:18:04Z) as a String, you can create a ZonedDateTime like this:
ZonedDateTime z = ZonedDateTime.parse("2017-06-22T16:18:04Z");
If you already have a java.util.Date object, you can convert it using org.threeten.bp.DateTimeUtils with a org.threeten.bp.ZoneOffset:
Date date = // get java.util.Date
ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneOffset.UTC);
In the end, the ZonedDateTime object will have the webPublicationDate value.
To get the different output formats, just create one DateTimeFormatter for each format. In the examples below, I also use java.util.Locale class to make sure the month names are in English:
// for Mar 3, 1984
DateTimeFormatter f1 = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);
// for 4:40 PM
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
// for 16:18
DateTimeFormatter f3 = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
System.out.println(f1.format(z)); // Jun 22, 2017
System.out.println(f2.format(z)); // 4:18 PM
System.out.println(f3.format(z)); // 16:18
The output is:
Jun 22, 2017
4:18 PM
16:18
Note that it uses the UTC timezone (the Z in 2017-06-22T16:18:04Z). If you want to display the date and time in another timezone, just use the org.threeten.bp.ZoneId class:
System.out.println(f3.format(z.withZoneSameInstant(ZoneId.of("Europe/London")))); // 17:18
The output is 17:18 (becase London is in summer time now).
Note that the API uses IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard. To find the timezone that better suits each region, use the ZoneId.getAvailableZoneIds() method and check which one fits best for your use cases.
If you don't want to add another dependency to your project and use SimpleDateFormat, you do something similar (create one parser and 3 output formatters, and use English locale). Also don't forget to set the timezone - I'm using UTC below, but you can change it to whatever timezone you want.
// parse date
String dateInString = "2017-06-22T16:18:04Z";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse(dateInString);
// create output formatters (set timezone to UTC)
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat s1 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
s1.setTimeZone(utc);
SimpleDateFormat s2 = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
s2.setTimeZone(utc);
SimpleDateFormat s3 = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
s3.setTimeZone(utc);
System.out.println(s1.format(date));
System.out.println(s2.format(date));
System.out.println(s3.format(date));
The output will be the same:
Jun 22, 2017
4:18 PM
16:18

java - String to Date Format

I have a problem with String conversion to Date Format. Please help me. Below is my code:
String strDate = "23/05/2012"; // Here the format of date is MM/dd/yyyy
Now i want to convert the above String to Date Format like "23 May, 2012".
I am using below code but i am getting value as "Wed May 23 00:00:00 BOT 2012"
String string = "23/05/2012";
Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(string);
System.out.println(date); // Wed May 23 00:00:00 BOT 2012
How can i get the value as "23 May, 2012". Please help me friends....
You must render the date again.
You have the string and you parse it correctly back to a Date object. Now, you have to render that Date object the way you want.
You can use SimpleDateFormat again, changing the pattern.
Your code should then look like
String string = "23/05/2012";
Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(string);
String newFormat = new SimpleDateFormat("dd MMMM, yyyy").format(date);
System.out.println(newFormat); // 23 May, 2012
Use the method format() from the class SimpleDateFormat with the correct pattern.
Simple use:
SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy");
System.out.println(df.format(date));
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws ParseException{
String strDate = "23/02/2012";
Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(strDate);
String date1 = new SimpleDateFormat("dd MMMM, yyyy").format(date);
System.out.println(date1);
}
}

SimpleDateFormat parse function changing the format

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

Categories