Random Number Change With Joda Time - java

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.

Related

random DateTime over a definite range

Hi looking for a sample code which will return a RandomDateTime as 1968-02-03 23:02:03 over a range (1960,1970).
YYYY-MM-DD HH:MM:SS.
my code is returning timezone in between which I don't want.
...
java.time
Random rand = new Random();
LocalDateTime minInclusive = LocalDateTime.of(1960, Month.JANUARY, 1, 0, 0);
LocalDateTime maxExclusive = LocalDateTime.of(1971, Month.JANUARY, 1, 0, 0);
int seconds = Math.toIntExact(ChronoUnit.SECONDS.between(minInclusive, maxExclusive));
int choice = rand.nextInt(seconds);
LocalDateTime randomDateTime = minInclusive.plusSeconds(choice);
System.out.println(randomDateTime);
Example output (from running just now):
1960-12-05T19:05:28
I am using LocalDateTime because you said you wanted no time zone, but you risk getting a non-exisitng time, typically a time in the spring gap when the clocks are turned forward when sumer time (DST) begins. To avoid this risk, use ZonedDateTime and specify the time zone. The code will be very similar to the above.
Calling between on ChronoUnit.SECONDS calculates elapsed time as whole seconds.
The call to Math.toIntExact is a safer way to go from a 64-bit long to an 32-bit int. Throws an exception if the value overflows.
The output from printing randomDateTime is in ISO 8601 format. If you want a different format (for example, without the T in the middle), you may format it using a DateTimeFormatter. Search for how.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You can get Randon date using ThreadLocalRandom class.
Here is quick fix for you. Please check following code.
Input :
Enter the Start Date: dd/mm/yyyy
01/01/1960
Enter the End Date: dd/mm/yyyy
01/01/1970
Output :
1969-04-18 06:30:54
Scanner input = null;
try {
input = new Scanner(System.in);
System.out.println("Enter the Start Date: dd/mm/yyyy");
String begin = new String();
begin = input.nextLine();
SimpleDateFormat startFormat = new SimpleDateFormat("dd/mm/yyyy");
Date startDate = startFormat.parse(begin);
System.out.println("Enter the End Date: dd/mm/yyyy");
String end = new String();
end = input.nextLine();
SimpleDateFormat endFormat = new SimpleDateFormat("dd/mm/yyyy");
Date endDate = endFormat.parse(end);
Date randomDate = new Date(ThreadLocalRandom.current()
.nextLong(startDate.getTime(), endDate.getTime()));
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String randomDateFormat = simpleDateFormat.format(randomDate);
System.out.println(randomDateFormat);
}
catch (Exception ex) {
ex.printStackTrace();
}finally{
input.close();
}
Hope this solution works.

Display and save only hours in int

How to display only hours and using int variable? I mean print time like 20:30:44 PM, I want to store only hours, mean 20 in int variable. how to do that?
Can anybody tell me the code if you know, thanks?
Try using Calendar's get method like:
Calendar c = ..
c.setTime(...);//if you have time in long coming from somewhere else
int hour = c.get(Calendar.HOUR_OF_DAY);
If you try to parse time from String I recommend these solutions:
String time = "20:30:44 PM"; // this is your input string
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss aa");
try {
Date date = sdf.parse(time);
// this is the uglier solution
System.out.println("The hour is: "+date.getHours());
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
// this is nicer solution
System.out.println("The hour is: "+gc.get(Calendar.HOUR_OF_DAY));
} catch (ParseException e) {
System.err.println("Couldn't parse string! "+e.getMessage());
}
date.getHours() and gc.get(Calendar.HOUR_OF_DAY) return int, in this example I printed it out without creating variable.
You can, of course, use regular expression to find out hour in your string but above solutions should do the trick. You can learn more about SimpleDateFormat and available patterns here. I hope I helped you a bit.
EDIT: In his comment autor noted, that date isn't static (like in String) but dynamic:
Calendar calendar = new GregorianCalendar();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
System.out.println("The hour is: "+hour);
I hope this helps.

Using calendars or Joda-Time in java

I have a document that starts on date X and end on date Y and and goes up by one day. My task is to go through this document and find out how many days are missing from the document.
Example:
19990904 56.00
19990905 57.00
19990907 60.00
Need to print out that 19900906 is missing.
I have done some research and read about java calendar, Date, and Joda-Time, yet was unable to understand what any of them are. Can some one please explain what these functions I just mentioned do, and then make a suggestion on how to use one to accomplish my goal?
I already have this code:
String name = getFileName();
BufferedReader reader = new BufferedReader(new FileReader(name));
String line;
while ((line = reader.readLine()) != null)
{ //while
String delims = "[ ]+";
String [] holder = line.split(delims);
// System.out.println("*");
int date = Integer.parseInt(holder[0]);
//System.out.println(holder[0]);
double price = Double.parseDouble(holder[1]);
With JodaTime. (If you are only concerned with date, you should NOT use datetimes, or mess with hours,minutes, dst issues.)
final DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMdd");
LocalDate date=null;
while( (line = getNextLine())!=null) {
String dateAsString = line.split(delims)[0];
LocalDate founddate = dtf.parseLocalDate(dateAsString);
if(date==null) { date= founddate; continue;} // first
if(founddate.before(date)) throw new RuntimeException("date not sorted?");
if(founddate.equals(date)) continue; // dup dates are ok?
date = date.plusDays(1);
while(date.before(foundate)){
System.out.println("Date not found: " +date);
date = date.plusDays(1);
}
}
If you only need to count missing days:
LocalDate date=null;
int cont=0;
while( (line = getNextLine())!=null) {
String dateAsString = line.split(delims)[0];
LocalDate founddate = dtf.parseLocalDate(dateAsString);
if(date==null) { date= founddate; continue;} // first
if(founddate.before(date)) throw new RuntimeException("date not sorted?");
if(founddate.equals(date)) continue; // dup dates are ok?
cont += Days.daysBetween(date, founddate)-1;
date = founddate;
}
LocalDate x = new LocalDate(dateX);
LocalDate y = new LocalDate(dateY);
int i = Days.daysBetween(x, y).getDays();
missingdays = originalSizeofList - i;
This is joda-time, its much easier than vanilla java.

Java format milliseconds to uu:mm:ss

I have the following problem and I couldn't find the best solution for it yet.
Lets say I have an integer with the following value:
int miliseconds = 65111;
I want to print it to an stream using the printf() function. Is there a way I can do the following:
printf("Time: %uu:mm:ssT", miliseconds");
so it will return:
Time: 00:01:05
Here I just made up the %uu:mm:ssT part, but is there a way to do this.
Also, do you know a website where I can find all the formatting options, so I can look it up myself next time.
Use
final int miliseconds = 65111;
System.out.printf("%1$TM:%1$TS.%1$TL\n", (long) miliseconds);
and see Format String Syntax for details.
Have a look at the SimpleDateFormat feature.
Consider the following sample
String inputPattern = ....
String outputPattern = ....
String ms = ((Integer) milliseconds).toString();
DateFormat inFormat = new SimpleDateFormat(inputPattern);
DateFormat outFormat = new SimpleDateFormat(outputPattern);
// Parse input
Date date = inFormat.parse(ms);
// Format the output
String output = outFormat.format(date);
[Edit] - Updated sample to only use j2se instead of including yodatime.
If you use the SimpleDateFormat to format a time from new Date(milliseconds), don't forget that SimpleDateFormat is time zone sensitive. So set it to UTC before using, like this:
DateFormat outFormat = new SimpleDateFormat("HH:mm:ss");
outFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = new Date(milliseconds);
String result = outFormat.format(d);
(I'm using a similar code in my program for a JSpinner to input a millisecond time value.)

how to find number of weekdays in array

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

Categories