i have an array of date. I want to find how many weekdays are in that array. So how can i do that using java..
*here i read lines from csv file & put those into values.
*values[2] contain the dates of that csv file.
*So now i want to find number of weekdays in values[2].
FileInputStream fis=new FileInputStream("c:/sample.csv");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader bf = new BufferedReader(isr);
while (bf.ready()) {
String line = bf.readLine();
String[] values=line.split(",");
String date=values[2];
}
here is my csv file
11/1/2010,jhone
11/3/2010,alex
11/6/2010,jhone
11/2/2010,neil
11/20/2010,neil
11/15/2010,jhone
String input = "11/1/2010";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/d/yyyy");
Date date = simpleDateFormat.parse(input);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
boolean isWeekday = dayOfWeek >= 2 && dayOfWeek <= 6;
System.out.println(isWeekday);
Or you could use the Joda-Time library.
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
String dayOfWeek = fmt.parseDateTime(values[2]).dayOfWeek().getAsText();
You could then do some comparison logic to check if the string is 'Saturday' or 'Sunday'. Joda-Time API also allows you to get the value as an int which means you just have to check if the integer returned is greater than 5 (1-Monday...7-Sunday).
// int weekDayCount = 0; // initialise this somewhere.
weekDayCount += ((fmt.parseDateTime(values[2]).dayOfWeek().get() < 6) ? 1 : 0);
Hope that helps.
I see you read them in as strings, but you didn't mention the format of the dates? (Like e.g. YYYY-MM-DD)
You should probably parse the string into a Date object (using DateFormat), and use that to set the time of a Calendar instance. With the calendar you can easily get the weekday from the date.
Check out Calendar class. It has the method that returns day of the week. You can then put a simple logic around it to figure out if its a week day or not.
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html
Related
I am working on android app with achartengine where I am making a TimeSeries linegraph. I have stored all my variables inside an Arraylist. Since I need correct date object to insert in the time axis of my chart I am using,
int count = list.size();
Date[] dt = new Date[count];
for(int i=0;i<count;i++){
long a = Long.parseLong(list.get(i).get("time"));
dt[i] = new Date(a);
}
Here long a has the timestamp . With above piece of code. I am able to get dt as 09-Apr-2014 but I need the date to be shown as 09-Apr 12:55 . How can I do that,
I tried using the folllowing
SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd HH:mm");
Date now = new Date();
String strDate = sdfDate.format(now);
But Since strDate is a string I cannot use it as dt[i] = strDate which will throws an error as one is Date and another is String.
How can I solve this ?
Thanks
You can solve it this way:
dt[i] = sdfDate.parse(strDate);
If you really just need the date strings, you can do this:
int count = list.size();
String[] dt = new String[count];
for (int i = 0; i < count; i++) {
long a = Long.parseLong(list.get(i).get("time"));
Date d = new Date(a);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
dt[i] = dateFormat.format(d);
}
Or, if you actually need the Date array, just format the dates on the fly as you need them.
Your question is misguided - you are showing how you create Date objects in the code, yet what you want to fix is how you show them.
The Date array will have dates precisely to the millisecond. The default toString() method of the Date objects shows only the day, that's why you're not seeing the time.
It is inherently the UIs responsibility to decide on the format of time that it is going to print, hence you should pass the Date array to the UI (or up to the point of printing) and format them there.
The DateFormat can do both (date to string representation and back):
DateFormat formatter = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss" );
Date to String:
Date date = new Date();
String sDate = formatter.format( time );
String to Date:
Date date = formatter.parse(sDate );
When you store the date, you should store it as precise as possible (milliseconds). For displaying it as a string, you can use whatever format you want.
My Joda Time is changing a number from 9 to 1 in my code.
Code:
String name = getFileName();
BufferedReader reader = new BufferedReader(new FileReader(name));
DateTime firstDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("YYYYMMDD");
String date = dtf.print(firstDate);
System.out.println(date);
String fake;
while ((fake = reader.readLine()) != null) {
String [] holder = fake.split(" ");
firstDate = dtf.parseDateTime(holder[2]);
System.out.println(holder[2]);
System.out.println(firstDate);
String useFirstDate = dtf.print(firstDate);
System.out.println(useFirstDate);
System.out.println("here");
break;
}
Output:
Please input File Name
futuresmin
201306172 //System.out.println(date);
19870901 //System.out.println(holder[2]);
1987-01-01T00:00:00.000-05:00 //System.out.println(firstDate);
19870101 //System.out.println(useFirstDate);
here //System.out.println("here");
I do not know if this is a common issue, or if it is just me, yet I have not found anything on the internet regarding this issue. Why would Joda Time change 19870901 to 19870101?
"DD" is day of year, not day of month, which is "dd". Your format string is incorrect.
On an unrelated note, it's difficult to correlate your output with your code. In general, it's best to keep the noise to a minimum, and make it explicit which output line comes from which code, like with a header.
I am getting a date from JSON file, and it is in string format.I have two string values of date named startdate and enddate that is coming from intent to currentActivity. Now I want to check that, if date value coming from json file is after the startdate or before the enddate. How can I do this? And yes, the format I json file having is "yyyy-mm-dd".
JSON Data Look like:
{"posts":[{"start_date":"2013-02-15","end_date":"2013-02-21"}]}
Here is the code I have tried but I am getting output as Mon Jan 07 00:00:00 GMT+5:30 2013:
Intent intent = getIntent();
String startDate = intent.getStringExtra("startDate"); //I have check this. It is proper.
String endDate = intent.getStringExtra("endDate"); //I have check this. It is proper.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date start = null,end = null;
try {
start = sdf.parse(startDate);
end = sdf.parse(endDate);
} catch (ParseException e1) {
e1.printStackTrace();
}
Here is the code of comparing date:
Date date = null;
try {
date = sdf.parse(c.getString(TAG_DATE)); //I am getting the date from a json file here.
} catch (ParseException e) {
e.printStackTrace();
}
Date currDate = new Date();
if (end.compareTo(currDate) < 0 || start.compareTo(currDate) < 0) {
Toast.makeText(getApplicationContext(),"Please select valid dates...",Toast.LENGTH_SHORT).show();
} else if (end.compareTo(currDate) == 0 && start.compareTo(currDate) >= 0){
if (date.after(start)) {
Toast.makeText(getApplicationContext(), "After...",Toast.LENGTH_SHORT).show();
}
} else if (end.compareTo(currDate) > 0 && start.compareTo(currDate) >= 0) {
if (date.after(start) && date.before(end)) {
Toast.makeText(getApplicationContext(),"Before...",Toast.LENGTH_SHORT).show();
}
}
I would prefer using a more robust approach that involves converting the date strings to actual Date (or Calendar) objects:
String startDateString = ...; // get date string from json
String endDateString = ...; // get date string from json
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date start = formatter.parse(startDateString);
Date end = formatter.parse(endDateString);
From here on, you can use e.g. start.before(end) or end.after(start) to check whether a date comes before or after another date. If you need more fine-grained control, you can always get the date in milliseconds and have your logic work on that.
So you've updated your code, but you're leaving it up to us to figure out what's going on and, more importantly, what you're expecting to happen? It looks like you want to check how the current date relates to those retrieved from json, although I'm a little lost at what the fourth date field, named date, is for.
Just some remarks about the current snippet:
if (end.compareTo(currDate) < 0 || start.compareTo(currDate) < 0)
Personally, I find before() and after() much more readable and descriptive, but I suppose there's nothing wrong with using compareTo(). However, important to realize is that 0 will only be returned iff the underlying millisecond representations of two dates are equal. With that being said, I'm not sure how much sense it would make to do the first check in the following condition:
else if (end.compareTo(currDate) == 0 && start.compareTo(currDate) >= 0)
You'll have to be really lucky to get the milliseconds of end exactly identical to currDate. Unless you do some manipulation somewhere to normalize all the dates to e.g. midnight, it's unlikely end.compareTo(currDate) == 0 will ever be true.
Regarding this normalization: have a look at the previously mentioned Calendar class. It'll allow you to easily retrieve the values for the separate fields of a datestamp/timestamp. For example, if you only want to compare the day, month and year, you can get those specific fields from a Calendar instance with a simple get call. Even more convenient is that you can also set every field independently - that's great for normalizing all dates to e.g. midnight or midday, after which you can still use the before() and after() methods.
I'm convinced that should give you enough pointers to correctly code up an implementation that fits your needs. Without exactly knowing what you're trying to achieve, I'm afraid I can't help you any further.
You can also try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
boolean isBefore = new Date().before(sdf.parse("2013-02-15",0));
http://developer.android.com/reference/java/text/SimpleDateFormat.html
http://developer.android.com/reference/java/util/Date.html
If you explode the date by dash - it will be easy to compare dates between mobile date and date by json. with easy compare logic you will get it.
String date = "2013-02-15";
String[] separated = date.split("-");
separated[0]; // this will contain "2013"
separated[1]; // this will contain "02"
separated[2]; // this will contain "15"
Calendar c1 = Calendar.getInstance();
String date = c1.get(Calendar.DAY_OF_MONTH);
Calendar ( to get mobile date )
http://developer.android.com/reference/java/util/Calendar.html
Hi I have the following date string format:
June-2008
July-2008
March-2010
May I enquire what is the java regex to extract out whatever the month and year value into separate string each. The delimeter here is the "-" sign
Any values from the start to the end of the "-" sign is the month, anything after the "-" sign is the year value.
The following is what I would like to achieve
String m = March
String y = 2010
Thank all for your help!
Don't use a regex. Use String#split():
String[] parts = "June-2008".split("-", 2); // or .split("-")
String m = parts[0]; // "June"
String y = parts[1]; // "2008"
Even better, use SimpleDateFormat, and you'll have a proper Date to work with:
DateFormat df = new SimpleDateFormat("M-y");
Date myDate = df.parse("June-2008");
I want to extend the answer given by Matt Ball. If you want to split that string and willing to use other than String#split() you can use StringUtils of Apache Commons Lang. It has various String utility methods.
An example:
String strDate = "June-2008";
String[] parts = StringUtils.split(strDate, '-');
String month = parts[0]; // "June"
String year = parts[1]; // 2008
Also if you want to get a java.util.Date object then Joda Time may helps you. I personally prefer this api rather java.util.Date as it is far more rich, easy-to-use, less error-pron.
Now we can manipulate that String as:
String strDate = "June-2008";
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM-yyyy");
DateTime dateTime = formatter.parseDateTime(strDate); // parse it
Date javaDate = dateTime.toDate(); // a java.util.Date object
int year = dateTime.getYear(); // 2008
String month = dateTime.month().getAsText(); // June
Hope this will help you. Thanks.
In my Java application I use a DateFormat instance to parse date inputs.
DateFormat fmt;
fmt = DateFormat.getDateInstance(DateFormat.DEFAULT) // dd.MM.yyyy for de_DE
The problem is that the user insists to enter dates in the form 31.12.11.
Unfortunately this is parsed to 31.12.11. (0011-12-31 in ISO format) Instead I want the parsed date to become 31.12.2011 (2011-12-31 in ISO format).
Can I modify the date format to somehow parse inputs that way?
You will have to parse with a format of dd.MM.yy and re-format with a format of yyyy-MM-dd
DateFormat sdfp = new SimpleDateFormat("dd.mm.yy");
Date d = sdfp.parse(input);
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd");
String date = sdff.format(d);
See the Java API for more info on setting patterns.
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Your solution here is sufficiently simple as to allow for the use of SimpleDateFormat, which includes the method set2DigitYearStart(Date startDate). Perhaps it looks something like this.
String userInput = "31.12.11";
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy");
format.set2DigitYearStart(new GregorianCalendar(2001,1,1).getTime());
Date userEnteredDate = format.parse(userInput, 1); // parsed to 2011-12-31
Yes, you could parse using DateFormat.SHORT instead of DEFAULT.
Or possibly, try to parse with SHORT, and then try other formats if that doesn't work.
You can parse this date using SimpleDateFormat but how you will determine that was 1911 or 2011 or anything else. you should use year format as yyyy.
If you use GWT, you don't have access to SimpleDateFormat, so here is some code to do it manually:
String[] parts = dateText.split(" ");
// Convert 2 digit date to 4 digits
if (parts.length == 3 && parts[2].length() == 2) {
int year = Integer.valueOf(parts[2]);
// Allow 5 years in the future for a 2 digit date
if (year + 100 > new Date().getYear()+5) {
year = year + 1900;
}
else {
year = year + 2000;
}
dateText = parts[0] + " " + parts[1] + " " + String.valueOf(year);
}
This assumes you have validated that the dateText is separated with spaces.
An approximation:
int twoDigitYear = 11;
int fourDigitYear = 0;
DateTime now = new DateTime();
if (twoDgYear + 2000 > now().getYear()) {
fourDigitYear = twoDigitYear + 1900;
}else{
fourDigitYear = twoDigitYear + 2000;
}
May or may not fit your need...