Remove specific words/strings from the list - java

How can we remove and preserve only Date from a String:
For ex: String outPut = {Time = 0:0:0} {Timestamp = Tue Oct 20 23:54:10 BST 2013}
I would like to have only Date
For ex: Tue Oct 20 2013
So far, I have tried the following approach:
String[] manipulateDate = output.getDate().split("\\{");
for(String s : manipulateDate ){
String outputDate = manipulateDate [2].replaceAll("\\}", "").replaceAll("\\s*\\bTimestamp =\\b\\s*","");
System.out.println(outputDate );
}
What is the best way to implement and use Java Date/String?

To strictly answer your question, you could do:
String date = output.replaceAll(".*Timestamp = (.*)? \\d{2}:.*?(\\d{4}).*", "$1 $2");
But it may be preferable to parse the whole string as a date object:
String output = "{Time = 0:0:0} {Timestamp = Sun Oct 20 23:54:10 BST 2013}";
String timestamp = output.replaceAll("\\{.*?\\} \\{Timestamp = (.*)\\}", "$1"); //Sun Oct 20 23:54:10 BST 2013
ZonedDateTime dateTime = ZonedDateTime.parse(timestamp, DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH));
From that point on, you can do what you want with the date object, including printing it as a string. Note that I changed the original string to Sunday (vs. Tuesday in your question): parsing it as a date also caught the fact that the 20th of October 2013 was not a Thursday, another advantage over strings.

Related

Comparing dates with months as strings

I am trying to compare these two dates :
17 Oct. 2019 (08:23)
19 déc. 2019 (21:15)
The months are in French and the main problem is the months. Do I need to put an if statement for every type of month so I can switch it with the appropriate month? For example:
if (MonthValue.equals("oct."){
DateValue.replace("oct.","10");
}
Or is there an easier solution, because I need to check in a table if the first value is bigger than the second one.
Edit :
My new Code :
String target1 = "17 oct. 2019 (08:23)";
String target2 = "19 déc. 2019 (21:15)";
DateFormat df = new SimpleDateFormat("dd MMM. YYYY (kk:mm)", Locale.FRENCH);
Date result = df.parse(target1);
Date result2 = df.parse(target2);
System.out.println(result);
System.out.println(result2);
if(result.compareTo(result2) < 0) {
System.out.println("true");
}
else {
System.out.println("false");
}
Doesn't work gives this error:
java.text.ParseException: Unparseable date: "17 oct. 2019 (08:23)"
java.time and optional parts in the format pattern string
Like the others I recommend that you use java.time, the modern Java date and time API, for your date and time work. I understand that if your month names are five letters or shorter (for example avril), they are written out in full, whereas if they are seven letters or longer (for example juillet), they are abbreviated. The following formatter can parse in both situations:
private static final DateTimeFormatter DATE_FORMATTER
= new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd [MMMM][MMM] uuuu (HH:mm)")
.toFormatter(Locale.FRENCH);
Square brackets [] in the format pattern string surround optional parts. MMMM is for full month name. MMM is for the abbreviation. So the point in [MMMM][MMM] is that it will successfully parse either full month name or abbreviations and just skip the one that doesn’t work. Since you gave an example of Oct. being written with an upper case O, I have also specified that the parsing should not be sensitive to case. If this is not necessary, you may use this simpler formatter:
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("dd [MMMM][MMM] uuuu (HH:mm)", Locale.FRENCH);
In order to check that all months work, I have set up these test data:
String[] dateStrings = {
"17 Oct. 2019 (08:23)",
"19 déc. 2019 (21:15)",
"01 avril 2021 (09:40)",
"08 janv. 2020 (01:18)",
"28 févr. 2021 (21:41)",
"03 mars 2020 (22:54)",
"06 mai 2020 (03:14)",
"21 juin 2020 (07:15)",
"18 juil. 2020 (23:06)",
"06 août 2020 (22:28)",
"29 sept. 2020 (06:04)",
"18 nov. 2019 (01:35)"
};
To parse and compare two of them use LocalDateTime.parse() and .isBefore():
LocalDateTime dateTime1 = LocalDateTime.parse(dateStrings[1], DATE_FORMATTER);
LocalDateTime dateTime2 = LocalDateTime.parse(dateStrings[2], DATE_FORMATTER);
if (dateTime1.isBefore(dateTime2)) {
System.out.format(Locale.FRENCH, "%s is before %s%n", dateTime1, dateTime2);
}
Output:
2019-12-19T21:15 is before 2021-04-01T09:40
For comparison you may also exploit the fact that LocalDateTime implements Comparable. This is practical when sorting the dates and times, for example. As a brief example let’s sort all the LocalDateTime objects that come out of parsing the above strings:
Arrays.stream(dateStrings)
.map(ds -> LocalDateTime.parse(ds, DATE_FORMATTER))
.sorted()
.forEach(System.out::println);
2019-10-17T08:23
2019-11-18T01:35
2019-12-19T21:15
2020-01-08T01:18
2020-03-03T22:54
2020-05-06T03:14
2020-06-21T07:15
2020-07-18T23:06
2020-08-06T22:28
2020-09-29T06:04
2021-02-28T21:41
2021-04-01T09:40
Link: Trail: Date Time (The Java™ Tutorials) explaining how to use java.time.
Using DateTimeFormatter with pattern dd MMM yyyy (HH:mm) to parse the date string like this
String target1 = "17 oct. 2019 (08:23)";
String target2 = "19 déc. 2019 (21:15)";
Locale locale = Locale.FRANCE;
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendPattern("dd MMM yyyy (HH:mm)")
.toFormatter(locale);
LocalDateTime dateTime1 = LocalDateTime.parse(target1, dateTimeFormatter);
LocalDateTime dateTime2 = LocalDateTime.parse(target2, dateTimeFormatter);
System.out.println(dateTime1);
System.out.println(dateTime2);
if (dateTime1.compareTo(dateTime2) < 0) {
System.out.println("true");
} else {
System.out.println("false");
}
My recommendation:
parse the dates e.g. with a DateTimeFormatter to e.g. a LocalDateTime
compare the parsed dates (most date and time objects implement https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Comparable.html)
What I've got from your question is that you want to convert Month's names to their respective numbers. If this is the case, then you should try switch
Example:
switch (MonthValue){
case jan:
MonthValue = 1; // Set Month variable to it Numbered Position (type casting might be required)
break;
case feb:
MonthValue = 2;
break;
default:
System.out.println("Somthing...");
}
Try encoding to UTF8, which will avoid DateTimeParseException
Exception in thread "main" java.time.format.DateTimeParseException: Text '19 d??c. 2019 (21:15)' could not be parsed at index 3
public static void main(String args[]) throws Exception {
String date1 = "17 oct. 2019 (08:23)";
String date2 = "19 déc. 2019 (21:15)";
DateTimeFormatter longDateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy (HH:mm)").withLocale(Locale.FRENCH);
LocalDateTime lclDate1 = LocalDateTime.parse(encodeUTF8(date1), longDateTimeFormatter);
LocalDateTime lclDate2 = LocalDateTime.parse(encodeUTF8(date2), longDateTimeFormatter);
if (lclDate1.compareTo(lclDate2) < 0) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
public static String encodeUTF8(String dateStr) {
byte[] bytes = dateStr.getBytes();
String utf8EncodStr = new String(bytes, StandardCharsets.UTF_8);
return utf8EncodStr;
}

Why my SimpleDateFormat is the same after parsing of concatenated string?

I have very strange situation. My date is not changing after I am using parse() method from SimpleDateFormat. I tried to search on another questions on the site but without any success. This is my code:
String CALENDAR_NO_TIMEZONE = "dd-M-yyyy hh:mm:ss a";
String CALENDAR_FORMAT = "dd-M-yyyy hh:mm:ss a Z";
String dateValue = new SimpleDateFormat(CALENDAR_NO_TIMEZONE).format(scheduledDate);
Date scheduledDate = new SimpleDateFormat(CALENDAR_FORMAT, Locale.US).parse(dateValue + " " + timeZoneAbbr);
For example my value for dateValue is "17-2-2021 12:15:00 AM", for timeZoneAbbr is "ACT" and for scheduledDate is "Wed Feb 17 0:15:00 CET 2021" before parsing, but also after parsing everything is the same, like this parse is not working. So where I am wrong?
Thanks in advance.

Difference of two dates in minutes

I have 2 dates in String with format (MMM dd, yyyy hh:mm:ss a).
How to convert two Strings into date and find the difference in minutes ?
DateFormat df = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.ENGLISH);
Date start = df.parse(startstring);
Date end = df.parse(endstring);
After I want to take the difference in minutes and I am using this code:
long result = ((end.getTime()/60000) - (start.getTime()/60000));
But the result is 0. How can I solve this problem ?
My Strings are :
start: Fri Mar 07 23:45:43 GMT+04:00 2014
end: Fri Mar 07 23:46:01 GMT+04:00 2014
You could use this approach (first calculate the minutes since epoch, then subtract them) -
private static long getTimeInMinutesFromEpoch(Date d) {
if (d == null) {
return 0;
}
return d.getTime() / (60 * 1000);
}
public static long getMinuteDifference(Date a, Date b) {
return Math.abs(getTimeInMinutesFromEpoch(b)
- getTimeInMinutesFromEpoch(a));
}
public static void main(String[] args) throws ParseException {
String startstring = "Mar 07, 2014 23:45:43 PM";
String endstring = "Mar 07, 2014 23:46:01 PM";
DateFormat df = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a",
Locale.ENGLISH);
Date start = df.parse(endstring);
Date end = df.parse(startstring);
System.out.println(getMinuteDifference(start, end));
}
Output is
1
From the looks of it you're creating the start date immediately before the end date (unless there is non-included relevant information).
Date start = df.parse(startstring);
Date end = df.parse(endstring);
These are going to be created in exactly the same minute and therefore give you 0 when you try to find the difference in minutes.
EDIT
Your times:
start: Fri Mar 07 23:45:43 GMT+04:00 2014
end: Fri Mar 07 23:46:01 GMT+04:00 2014
are 18 seconds apart. You're going to get 0 for the difference in minutes.
You can make Calendar object instead of Date and then you can get the minutes using Calendar.get(Calendar.MINUTE). Note that by using this logic, the difference between 22:45:43 GMT+04:00 2014 and 23:45:43 GMT+04:00 2014 will be zero minutes.

how to compare two dates in java in a simple way

I want to know if there is a simple way to compare two dates of this format for example :
Wed, 31 Jul 2013 09:31:51
Mon, 05 Aug 2013 10:18:24
and display the greatest date?
I'd suggest you to use Joda library. Using the date info you have, create DateTime instances and call isBefore() method to determine which one comes first.
I would check the documentation, which shows that Date implements Comparable<Date> and so
date1.compareTo(date2);
will do what you want. You may wish to ensure that date1 is not null.
If your dates are (in fact) Strings, then use SimpleDateFormat's parse() method to convert from strings to dates, and then perform that comparison.
As others have suggested, Joda is a better date/time library (better API and threading performance).
Date d1, d2;
This returns greatest dates:
d1.after(d2) ? d1 : d2;
first parse the string into a Date object using a SimpleDateFormat :
String dateStringA = "Wed, 31 Jul 2013 09:31:51";
String dateStringB = "Mon, 05 Aug 2013 10:18:24";
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss");
Date dateA = parserSDF.parse(dateStringA);
Date dateB = parserSDF.parse(dateStringB);
if (dateA.compareTo(dateB) > 0) {
System.out.println("A bigger");
}
then compare the Date objects using compareTo method
You can use Date's getTime() method and then use < >.
This will work for you
DateFormat df=new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
Date date1=df.parse("Wed, 31 Jul 2013 09:31:51");
Date date2=df.parse("Mon, 05 Aug 2013 10:18:24");
System.out.println(date1.after(date2) ? date1 : date2);

Working with Dates in Java

I need to work with dates and I wasn't sure how to go about that in Java since I have never done it before.
I am pulling dates from the Excel file and they can be retrieved in the Data format which would represent the date.
Ex:
2/1/2010
5/12/2011
8/15/2011
9/1/2011
9/1/2011
All my codes are pretty irrelvent to the question, but I am setting up a getter/setter method:
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
So my question is this, in what way when I am pulling the data from Excel:
temp.setDate((row.getCell(3).getDateCellValue());
I can set the limit so it only retrieves data from x amount of months. 8, 12, et.. from the last month/year displayed in the file, instead of going back all the way to 2010? I can provide more details if needed.
Edit: This is what I have now:
import java.util.Date;
Date date;
date = row.getCell(3).getDateCellValue();
It shows: Tue June 01 00:00:00
I don't care about Tuesday or 00:00:00, I just have a whole list of data and I only want to show x amount of months.
Edit: I figured it out. :)
The question is pretty vague, but if you are using Excel I have found it very beneficial to save the file as a 'filename.csv'. This format very easy to work with, it is comma delimited going across and newlines going down. If you are periodically checking the month, it would be easy to ensure that you only go x months backwards.
First you need to parse the dates accordingly using the SimpleDateFormat class. The result is a date object.
SimpleDateFormat df = new SimpleDateFormat( "M/d/yyyy" );
Date date = df.parse(row.getCell(3).getDateCellValue());
Then:
Calendar cal = Calendar.getInstance();
will return you an object ob type Calendar, where you can set the date by
cal.setTime(date);
Finally your loop reading the Excel file can determine according to the calendar object, if the date should be included / further processed by using:
int month = cal.get(Calendar.MONTH); // e.g. 11 for Nov
int year = cal.get(Calendar.YEAR); // e.g. 2011
You have to work with DateFormat.class fo parse the cell, or use a Calendar to put Day Month Year
EDIT
You can also use Calendar.class
final String[] tabDate = {"2/1/2010", "5/12/2011", "8/15/2011",
"9/1/2011", "9/1/2011"};
// Extract field's value
final Calendar c = Calendar.getInstance();
// Parse the list of stringDate
for (final String string : tabDate) {
System.out.println("Input string: " + string);
final String[] shortDate = string.split("/");
// Build Calendar
c.set(Integer.valueOf(shortDate[2]), Integer.valueOf(shortDate[0]),
Integer.valueOf(shortDate[1]));
// Extract date as you like
System.out.format("%25s : %d/%d/%d\t%s\n\n", c.getTime(),
c.get(Calendar.MONTH), c.get(Calendar.DATE),
c.get(Calendar.YEAR), c.getTimeInMillis());
}
Console :
Input string: 2/1/2010
Mon Mar 01 09:09:48 CET 2010 : 2/1/2010 1267430988109
Input string: 5/12/2011
Sun Jun 12 09:09:48 CEST 2011 : 5/12/2011 1307862588109
Input string: 8/15/2011
Thu Sep 15 09:09:48 CEST 2011 : 8/15/2011 1316070588109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109
Input string: 9/1/2011
Sat Oct 01 09:09:48 CEST 2011 : 9/1/2011 1317452988109

Categories