Not able to parse the date in US format in java - java

I have the below java program in which you specify the parameter in which format you want to convert date that is whether you want to convert it in US or UK format.
Now the problem is that when i want date to be formatted as per US format it does not do that , request you to please advise what is missing in this format ,below is program and output which is there when i try to convert it in US format
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.lang.time.DateUtils;
public class DateFormattingTest {
public static void main(String[] args) throws ParseException {
System.out.println ("01-Mar-2016-->" + extractDate("01-Mar-2016", "US") );
}
public static java.util.Date extractDate(String dateStr, String dateType) {
java.util.Date date = null;
if (!dateStr.matches("\\d{4}-\\d{2}-\\d{2}")){
String[] datePatternsOfUk = { "d-M-yy", "d-M-yyyy", "d/M/yy", "d/M/yyyy", "yyyy-MM-dd","dd-MM-yy", "dd-MMM-yy","dd-MMM-yyyy","dd-MM-yyyy",
"dd/MM/yy","dd/MMM/yy","dd/MMM/yyyy"};
String[] datePatternsOfUs = { "M-d-yy","MM-dd-yy","M/d/yy","MM/dd/yy", "MM/dd/yy", "MMM-dd-yy",
"MMM/dd/yy", "MMM-dd-yyyy", "MM-dd-yyyy", "MMM/dd/yyyy",
"MM/dd/yyyy" };
String[] datePatterns = datePatternsOfUk;
try {
if (dateType.equals("US")) {
datePatterns = datePatternsOfUs;
} else if (dateType.equals("UK")) {
datePatterns = datePatternsOfUk;
}
int p = dateStr.lastIndexOf("/");
if (p == -1) {
p = dateStr.lastIndexOf("-");
}
String firstSubstring = dateStr.substring(0, p + 1);
String secondSubstring = dateStr.substring(p + 1);
if (p != -1 && secondSubstring.length() <= 2) {
secondSubstring = Integer.toString(2000 + Integer.parseInt(secondSubstring));
dateStr = firstSubstring + secondSubstring;
}
date = DateUtils.parseDate(dateStr, datePatterns);
} catch (ParseException e) {
}
return date;
}
if (dateStr.matches("\\d{4}-\\d{2}-\\d{2}")){
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String convertedCurrentDate =sdf.format(sdf.parse(dateStr));
date=sdf.parse(convertedCurrentDate);
} catch (ParseException e) {
}
return date;
}
return null;
}
}
The output that i am getting on US format is shown below..
01-Mar-2016-->null
Actually in US format i am expecting the date to be display as
01-Mar-2016--> 3-Jan-2016
folks please advise for this is my expected result is not correct one as per US format

01-Mar-2016 isn't in a format you have defined for US. Add dd-MMM-yyyy to datePatternsOfUs like
String[] datePatternsOfUs = { "M-d-yy","MM-dd-yy","M/d/yy","MM/dd/yy",
"MM/dd/yy", "MMM-dd-yy", "MMM/dd/yy", "MMM-dd-yyyy",
"MM-dd-yyyy", "MMM/dd/yyyy", "MM/dd/yyyy", "dd-MMM-yyyy" };

Related

How to show data in java fx 8 table view existing between two timestamps

I have a question that I couldn't find a solution for.
I'm trying to filter my javafx8 tableview but i'm facing a problem .
I don't know how to show only data existing between two time stamps.
Edit : to be explicit i want to know how to configure a beginnig and an ending for the rows using text field
PS : screenshot of my tableview :
I have already seen https://code.makery.ch/blog/javafx-8-tableview-sorting-filtering/. I have a trouble with creating a proper Predicate, in the tuto they show you how to display only informations that have the same informations. and i want to display the infos existing in between.
PS: item type is Timestamp
confirmdatebtn1.setOnAction(new EventHandler<ActionEvent>(){
#Override public void handle(ActionEvent e) {
filterData.setPredicate(table -> {
if ((todatetxt.getText() == null &&fromdatetxt.getText() == null) ||
(todatetxt.getText().isEmpty()&&fromdatetxt.getText().isEmpty()) ) {
return true;}
try {
String fromtext = fromdatetxt.getText();
String totext = todatetxt.getText();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date date1 = null;
Date date2 = null;
Timestamp timestamp1 = null;
Timestamp timestamp2 = null;
if(todatetxt.getText().isEmpty() && !fromdatetxt.getText().isEmpty()) {
date1 = format.parse(fromtext+" 00:00:00.000");
timestamp1 = new java.sql.Timestamp(date1.getTime());
if (table.getTime_of_action().after(timestamp1) )
{return true;}
}
if(!todatetxt.getText().isEmpty() && fromdatetxt.getText().isEmpty()) {
date2 = format.parse(totext+" 23:59:59.000");
timestamp2 = new java.sql.Timestamp(date2.getTime());
if (table.getTime_of_action().before(timestamp2) )
{return true;}
}
if(!todatetxt.getText().isEmpty() && !fromdatetxt.getText().isEmpty()) {
date1 = format.parse(fromtext+" 00:00:00.000");
date2 = format.parse(totext+" 23:59:59.999");
timestamp1 = new java.sql.Timestamp(date1.getTime());
timestamp2 = new java.sql.Timestamp(date2.getTime());
if (table.getTime_of_action().before(timestamp2) &&table.getTime_of_action().after(timestamp1))
{return true;}
}
} catch (Exception e1) {
}
return false;
});} });*** i wrote this code and it came out good so my probleme is resolved thanks to your help guys***

JAVA8, parsing text file and parsing its values to objects

I have specific text file looking like this:
name: meeting_name1
description:
04/18/2012 00:00:00
05/18/2012 00:00:00
... (more dates)
07/18/2012 00:00:00
name: meeting_name2
description: some_desc
04/18/2012 00:00:00
05/18/2012 00:00:00
... (more dates)
07/18/2012 00:00:00
(etc)
I have java object looking like this:
class Meeting {
String name;
String description;
List<Date> dates;
}
My point is to read the file, parse values, create objects and save them to database.
I can read the file line by line and convert it to List<String>, ie. all data together.
`I can make and fill one java object with values and save it to database.
My issue here is how to find out that I'm at the end of dates and lines (name: meeting_name2) of new object begin.
So I could make something like List<List<String>> where List<String> would be equal to one object, ie. List<Meeting>?
Not sure if its understandable, sorry for formatting.
Assumption that you could read the file data to List variable. (See above answer)
List<String> lines = Files.readAllLines(Paths.get("FILE_NAME"));
Now, you can see below code as a demo. It is the simple loop and if else statament.
Hope it will help you.
public static void main(String[] args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
List<String> data = new ArrayList<>();
data.add("name: meeting_name1");
data.add("description: some_desc");
data.add("07/18/2012 00:00:00");
data.add("07/18/2012 00:00:00");
data.add("name: meeting_name2");
data.add("description: some_desc");
data.add("07/18/2012 00:00:00");
List<Meeting> result = new ArrayList<>();
Meeting temp = null;
for (String line : data) {
if (line.startsWith("name:")) {
temp = new Meeting(line.split(":")[1].trim());
result.add(temp);
} else if (line.startsWith("description:")) {
temp.setDescription(line.split(":")[1].trim());
} else {
temp.getDates().add(simpleDateFormat.parse(line)); // Use date for
}
}
System.out.println(result.get(0).getName() + ": " + result.get(0).getDates().size()); // meeting_name1: 2
System.out.println(result.get(1).getName() + ": " + result.get(1).getDates().size()); // meeting_name2: 1
}
static class Meeting {
String name;
String description;
List<Date> dates;
public String getName() {
return name;
}
public List<Date> getDates() {
return dates;
}
Meeting(String name) {
this.name = name;
this.dates = new ArrayList<>();
}
public void setDescription(String description) {
this.description = description;
}
}
One possibility would be to read all lines first. You would not need to worry about the end of lines with:
List<String> lines = Files.readAllLines(Paths.get("FILE_NAME"));
then iterarate through the array,
if a line starts with "name:" you make a new object and add the data like that:
List<Meeting> meetings = new ArrayList();
Meeting currentMeeting;
for (String line : lines) {
if(line.startsWith("name:"))
{
currentMeeting = new Meeting();
meetings.add(currentMeeting);
//...add data (name)
}
//...add more data (description and dates)
}

Check whether dates are within the date range in selenium web driver ( Java)

In my website, I can select a date range and list all the transactions within the date range. My test case is to verify whether listed transactions dates are within the selected date range .
This is my code. I get all the transaction dates into a LinkedList. Comp_Dates method will compare the actual date is within the ‘From’ and ‘To’ dates.
The problem is this code will always return True. I have changed the FromDate and ToDate to test the false scenario, But still code will return True.
Can you please help? What’s the problem in this code?
//Set From Date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateFrom_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"),"01/03/2016");
//Set To date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateTo_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"),"30/04/2016");
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_btnList")).click();
List<WebElement> Date =
driver.findElements(By.xpath(".//* [#id='ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_stxOutstandingTransactions_gvOSTransactions']/tbody/tr[*]/td[1]"));
List<String> Dates = new LinkedList<String>();
for(int i=0;i<Date.size();i++)
{
Dates.add(Date.get(i).getText());
System.out.println(Dates);
}
boolean result = comp_Dates(Dates);
if (result=true)
{
System.out.println(result + ", Address are within the range");
}
else
{
System.out.println(result + ", Addresses are not within the range. Test Case Failed");
}
}
private static boolean comp_Dates(List<String> Dates) {
try
{
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
//Date date = fmt.parse("2013-05-06");
String FromDate= "01/05/2016";
String ToDate= "30/06/2016";
java.util.Date Fdate =fmt.parse(FromDate);
java.util.Date Tdate =fmt.parse(ToDate);
for(String e : Dates)
{
java.util.Date ActualDate = fmt.parse(e);
if (ActualDate.compareTo(Fdate)>=0 & ActualDate.compareTo(Tdate)<=0 );
{
return true;
}
}
}
catch (Exception ex ){
System.out.println(ex);
}
return false;
}
}
Transactions dates in Linked list is [18/04/2016, 14/04/2016, 13/04/2016]
I have specified dates as below in the code.
String FromDate= "01/05/2016";
String ToDate= "30/06/2016";
When compare these dates, code should return false as dates doesn’t fall on within From and To dates. But it returns True. What am I doing wrong here?
Thanks
When you are returning true, it will exit the function whenever it founds a date in the range. Thus it would not check for all dates in the list.
If you want to check for all dates, proper comp_Dates method could be:
//Set From Date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateFrom_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"), "01/03/2016");
//Set To date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateTo_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"), "30/04/2016");
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_btnList")).click();
List<WebElement> Date =
driver.findElements(By.xpath(".//* [#id='ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_stxOutstandingTransactions_gvOSTransactions']/tbody/tr[*]/td[1]"));
for (int i = 0; i < Date.size(); i++) {
String date = Date.get(i).getText();
boolean result = comp_Dates(date);
if (result) {
System.out.println(result + ", Address are within the range");
} else {
System.out.println(result + ", Addresses are not within the range. Test Case Failed");
}
}
private static boolean comp_Dates(String date) {
try {
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
String FromDate = "01/05/2016";
String ToDate = "30/06/2016";
java.util.Date Fdate = fmt.parse(FromDate);
java.util.Date Tdate = fmt.parse(ToDate);
java.util.Date ActualDate = fmt.parse(date);
if (ActualDate.compareTo(Fdate) >= 0 && ActualDate.compareTo(Tdate) <= 0) {
return true;
}
} catch (Exception ex) {
System.out.println(ex);
}
return false;
}
N.B: There are many typos in your code. You should fix these.

SimpleDateFormat RegEx formats

Regex master needed!
I have an variable timestamp coming from the server and I need to find which format is used everytime. I've tried implementing a regex formats but they don't work. I'm fairly new to regex patterns but still I've tried working them up my self or else look for a specific example but couldn't find so I'm asking you.
The formats from the server can look like this:
"2015-02-23 15:27:31 UTC"
or
"2015-01-22T19:38:40Z"
here is the code to find the formats:
private static String getFormat(String time) {
String firstRegEx = "^\\d{4}-\\d{2}-\\d{2}\'T+\'\\d{2}:\\d{2}:\\d{2}\'Z\'$";
String secondRegEx = "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s\\w{3}$";
if (time.toLowerCase().matches(firstRegEx)) {
return firstRegEx;
} else if (time.toLowerCase().matches(secondRegEx)) {
return secondRegEx;
}
return null;
}
Can you look at my regex patterns and tell me what am I doing wrong?
First you have to remove the single quotes arround the char Tand Zand second you call toLowercase() wich will canvert T to t and Z to z. remove it:
private static String getFormat(String time) {
String firstRegEx = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$";
String secondRegEx = "^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s\\w{3}$";
if (time.matches(firstRegEx)) {
return firstRegEx;
} else if (time.toLowerCase().matches(secondRegEx)) {
return secondRegEx;
}
return null;
}
^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$
Your first regex should be simply this.This will match 2015-01-22T19:38:40Z.See demo.
https://regex101.com/r/aI4rA5/4
Your second regex works fine.
I believe this is the alternative solution suggested in the comments...
public static void main(String[] args) {
System.out.println(getFormat("2015-02-23 15:27:31 UTC"));
System.out.println(getFormat("2015-01-22T19:38:40Z"));
}
private static DateFormat getFormat(String time) {
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
if (isFormat(format1, time)) {
return format1;
} else if (isFormat(format2, time)) {
return format2;
} else {
return null;
}
}
private static boolean isFormat(DateFormat format, String candidate) {
return format.parse(candidate, new ParsePosition(0)) != null;
}
If you were using the regex to decide how to parse later on you could bundle this into a single method capable of consuming multiple formats...
public static void main(String[] args) {
System.out.println(getDate("2015-02-23 15:27:31 UTC"));
System.out.println(getDate("2015-01-22T19:38:40Z"));
}
private static Date getDate(String time) {
DateFormat[] formats = { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z") };
Date date = null;
for (DateFormat format : formats) {
if ((date = format.parse(time, new ParsePosition(0))) != null) {
break;
}
}
return date;
}
If these are the only possible formats then it is enough to test if date.charAt(10) == 'T'

How to validate Hour and Minutes that came from a Swing textBox?

I have a window that contains a HH:mm time TextField in it, in 24 hours format
I need to validate if the user entered any non valid hour, like 28:00, 99:00, 24:01.
What's the best and simpler way to do that ?
some code below of what is currently doing that job wrong and giving errors in date parsed.
Today I get an random hour and an user hit 99:99 in that text field.
This code is not mine, but I gotta fix it.
I am stuck with it, tried to validate as a String is useless, and I cannot find a nice way to make it a Date without having to put year, month, etc... too.
Please forget about the return -1 instead of throwing an exception this is old code and this cannot be changed.
to help understand :
Statics.hF2 = SimpleDateFormat (HH:mm)
this.cmpHora.getText() = Is the field with the value
Statics.df_ddmmyy = Another date format
Statics.m2ms = converts minutes to milliseconds
//CODE
public long getDataEmLong ()
{
try
{
Calendar hour= Calendar.getInstance();
new GregorianCalendar().
hour.setTime( Statics.hF2.parse( this.cmpHora.getText() ) );
return Statics.df_ddmmyy.parse( this.cmpData.getText() ).getTime() + Statics.m2ms( hour.get( Calendar.HOUR_OF_DAY ) * 60 ) + Statics.m2ms( hour.get( Calendar.MINUTE ) );
} catch ( Exception e )
{
e.printStackTrace();
return -1;
}
}
Cheers !
Regular expressions to the rescue:
public boolean validTime24(String time) {
return time.matches("^([01]\d|2[0-3]):[0-5]\d$")
}
This will validate the format of the string. Then you can parse out the time from there.
Insert this in your class, and perform the validateTime method from inside your junk code.
public boolean validateTime(String timeString) {
if (timeString.length() != 5) return false;
if (!timeString.substring(2, 3).equals(":")) return false;
int hour = validateNumber(timeString.substring(0, 2));
int minute = validateNumber(timeString.substring(3));
if (hour < 0 || hour >= 24) return false;
if (minute < 0 || minute >= 60) return false;
return true;
}
public int validateNumber(String numberString) {
try {
int number = Integer.valueOf(numberString);
return number;
} catch (NumberFormatException e) {
return -1;
}
}
You can use JFormattedTextField with proper Date or Time Format set. The field will return you proper values.
Since Java 8 you can use DateTimeFormatter:
public boolean validate(String time) {
try {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
timeFormatter.parse(time);
return true;
} catch (DateTimeParseException e) {
return false;
}
}

Categories

Resources