I'm reading the data from CSV file. One of the fields is the time in the format H:mm, i.e. "8:00". How to convert this string value into the minutes (integer value), i.e. 8:00 = 8*60 = 480 minutes?
String csvFilename = "test.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
csvReader.readNext(); // to skip the headers
int i = 0;
while((row = csvReader.readNext()) != null) {
int open = Integer.parseInt(row[0]);
}
csvReader.close();
You can use java.text.SimpleDateFormat to convert String to Date. And then java.util.Calendar to extract hours and minutes.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse("8:00");
cal.setTime(date);
int mins = cal.get(Calendar.HOUR)*60 + cal.get(Calendar.MINUTE);
Try something like this
String str = "8:10";
int minutes=0;
String[] arr= str.split(":");
if(arr.length==2){
minutes=Integer.parseInt(arr[0])*60+Integer.parseInt(arr[1]);
}
System.out.println(minutes);
Write something like this to convert into int
public int convertToMin(String hrmin) {
String[] tokens = hrmin.split(":");
int minutes = 0;
for (int i = tokens.length; i > 0; i--) {
int value = Integer.parseInt(tokens[i - 1]);
if (i == 1) {
minutes += 60 * value;
}
else {
minutes += value;
}
}
return minutes;
}
Try this
String str = "8:20";
int ans = (Integer.parseInt(str.split(":")[0])* 60)+Integer.parseInt(str.split(":")[1]);
System.out.println("Answer = "+ans);
Related
I want to set text by date and incrementing loop, and when the day changes looping start from the beginning.
Example
1. day 1 =
a. nameFile 110920190001
b. nameFile 110920190002, etc.
2. day 2 =
a. nameFile 120920190001
b. nameFile 120920190002, etc.
Code
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
for(int i = 1; i <= 1000; i++) {
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
Just put the Date Initialization in the for loop for it to always take the new Instance of the date.
public static void replace(String s) {
for (int i = 1; i <= 1000; i++) {
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
}
I use the code below to see if my input date (format mm/dd/yyyy HH:mm:ss) falls within the range of startDate and endDate.
I use compareTo() in this logic. But with the format mm/dd/yyyy, it compares the month alone and prints output in "MYLOGIC methood". But I need the year to be compared to see if the input date is within startDate and endDate range.
public class DateLogicNew {
public static void main(String[] args) {
String startDate[] = new String[1];
String endDate[] = new String[1];
startDate[0] = "01/01/0600 00:00:00";
endDate[0] = "11/27/3337 00:00:00";
String inputArr[] = { "05/01/0500 01:00:00", "11/27/3337 00:00:00",
"05/05/0700 00:00:00", "11/27/2337 00:00:00",
"06/05/4000 00:00:00" };
String protectedArr[] = new String[inputArr.length];
int temp[] = new int[inputArr.length];
System.out.println(inputArr.length);
System.out.println("Length of the inputArr: " + inputArr.length);
// System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (inputArr[i]
.matches("^([0-1][0-9])/([0-3][0-9])/([0-9]{4})(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
System.out.println("Inside if loop");
if (inputArr[i].compareTo(startDate[0]) > 0
&& inputArr[i].compareTo(endDate[0]) < 0) {
System.out.println("inside the compare condition");
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in MYLOGIC method : "
+ protectedArr[i]);
}
} else {
temp[i] = 0;
}
}
System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (temp[i] == 1) {
inputArr[i] = protectedArr[i];
}
System.out
.println("Final Value to the output port: " + inputArr[i]);
}
}
}
java.time
Parse as date-time objects. Regex is overkill.
The modern approach uses the java.time classes rather than the old legacy date-time classes.
String input = "05/01/0500 01:00:00" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Compare using methods isBefore, isAfter, isEqual.
if( ( ! x.isBefore( start ) ) && x.isBefore( stop ) ) { … }
I myself figured out the solution for my question. Please check the code below to see the logic before comparing the dates.
String startDate = "0600/01/01 00:00:00";
String endDate = "3337/11/27 00:00:00";
try {
for (int i = 0; i < inputArr.length; i++) {
String newDateInput = inputArr[i];
// System.out.println("NewInput:" + newInput);
DateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date convertedDate = parser.parse(newDateInput);
String newFormattedInput = formatter.format(convertedDate);
// System.out.println("newFormattedInput: " +
// newFormattedInput);
if (newFormattedInput
.matches("^([0-9]{4})/([0-1][0-9])/([0-3][0-9])(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
if (newFormattedInput.compareTo(startDate) > 0
&& newFormattedInput.compareTo(endDate) < 0) {
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in PROTECT method : "
+ protectedArr[i]);
} else {
temp[i] = 0;
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
My requirements:
ddmm + 2numbers
dd - day
mm - month
number - id number
Examples of my output
Today - 031201, 031202, 031203 ...
Tommorrow - 041201
Properties file: (idNumber.properties)
idNumber = 1;
Here is the java code I did:
public class Test{
public static void main(String[] args)
{
Test test = new Test();
test.generate();
}
public String generate()
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber();
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(){
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
My question is how do I reset the tommorrow id number start from 01?
You can add a property LAST_VISIT to your properties file. When you want to save the properties file, set the current date to it. In this way
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
idNoProp.setProperty("LAST_VISIT", currentDate);
Now in generateIdNumber() first check the value of LAST_VISIT. If it dose not equal currentDate , you must reset idNo. It works for everyday and every tommorow.
Try to put a class static field to remember last used date for ids. Whenever you are in the next date relatively to the field you'll reset your idNo and update the last used date field (sorry for spelling)
You can store a Map<String,Integer> that would hold the last index for each String representation of date. This way, each date would have its own indices starting with 1.
You can run a scheduler which will reset the idNo at the start of each day, like at 00 hours. This will always gives you the consistent result, as if sometimes server/program restarts, it will not lead to any duplicate result.
if you want format a number with two number, example '01' you could do this:
String.format("%02d", Integer.valueOf(idNumber));
instead of:
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
public class Test{
public static void main(String[] args) throws IOException
{
Test test = new Test();
System.out.println(""+test.generate());
}
public String generate() throws IOException
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber(currentDate);
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(String currentDate) throws IOException{
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String strOnlyDay = currentDate.substring(0, 2);
System.out.println(strOnlyDay);// will return the first two characters of the day
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
if (strOnlyDay.equals("01")){
idNo = 1;
}
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
Try to pass the value of your current date into generateIdNumber than see the code. I hope this will help. Hoping you will preserve the value of idNo.
I'm able to get current week dates, But How to list previous / next week days ?
This is the method
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
// System.out.println(Arrays.toString(days));
return days;
}
pls see the image, and tell me how to get the next and previous week days
finally i got the answer pls see this
Get the present Week:
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the Next Week:
int weekDaysCount=0;
public String [] getWeekDayNext()
{
weekDaysCount++;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the previous Week:
public String [] getWeekDayPrev()
{
weekDaysCount--;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
to assign the textView
NextPreWeekday = getWeekDay();
firstDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [0]);
lastDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [6]);
textViewDate.setText(firstDayOfWeek + "-" + lastDayOfWeek + " " + CommonMethod.convertWeekDaysMouth(NextPreWeekday [6]));
textViewSun.setText(CommonMethod.convertWeekDays(NextPreWeekday [0]) + "\nSun");
textViewMon.setText(CommonMethod.convertWeekDays(NextPreWeekday [1]) + "\nMon");
textViewTue.setText(CommonMethod.convertWeekDays(NextPreWeekday [2]) + "\nTue");
textViewWed.setText(CommonMethod.convertWeekDays(NextPreWeekday [3]) + "\nWeb");
textViewThu.setText(CommonMethod.convertWeekDays(NextPreWeekday [4]) + "\nThu");
textViewFri.setText(CommonMethod.convertWeekDays(NextPreWeekday [5]) + "\nFri");
textViewSat.setText(CommonMethod.convertWeekDays(NextPreWeekday [6]) + "\nSat");
public static String convertWeekDays(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("dd");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
public static String convertWeekDaysMouth(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("MMM yyyy");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
For current week.
SimpleDateFormat displayDate = new SimpleDateFormat("dd-MMM-yyyyy"));
final Calendar calenderThisWeek = Calendar.getInstance();
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
For Previous Week
final Calendar calenderpreviousWeek = Calendar.getInstance();
calenderpreviousWeek.add(Calendar.DAY_OF_WEEK, -1);
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderpreviousWeek.getTime()); // dd-mmm-yyyy
For Next Week
final Calendar calenderNextWeek = Calendar.getInstance();
calenderNextWeek.add(Calendar.DAY_OF_WEEK, +1);
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy
I have a problem with my code. I need to do several operations on a log file with this structure:
190.12.1.100 2011-03-02 12:12 test.html
190.12.1.100 2011-03-03 13:18 data.html
128.33.100.1 2011-03-03 15:25 test.html
128.33.100.1 2011-03-04 18:30 info.html
I need to get the number of visits per month, number of visits per page and number of unique visitors based on the IP. That is not the question, I managed to get all three operations working. The problem is, only the first choice runs correctly while the other choices just return values of 0 afterwards, as if the file is empty, so i am guessing i made a mistake with the I/O somewhere. Here's the code:
import java.io.*;
import java.util.*;
public class WebServerAnalyzer {
private Map<String, Integer> hm1;
private Map<String, Integer> hm2;
private int[] months;
private Scanner input;
public WebServerAnalyzer() throws IOException {
hm1 = new HashMap<String, Integer>();
hm2 = new HashMap<String, Integer>();
months = new int[12];
for (int i = 0; i < 12; i++) {
months[i] = 0;
}
File file = new File("webserver.log");
try {
input = new Scanner(file);
} catch (FileNotFoundException fne) {
input = null;
}
}
public String nextLine() {
String line = null;
if (input != null && input.hasNextLine()) {
line = input.nextLine();
}
return line;
}
public int getMonth(String line) {
StringTokenizer tok = new StringTokenizer(line);
if (tok.countTokens() == 4) {
String ip = tok.nextToken();
String date = tok.nextToken();
String hour = tok.nextToken();
String page = tok.nextToken();
StringTokenizer dtok = new StringTokenizer(date, "-");
if (dtok.countTokens() == 3) {
String year = dtok.nextToken();
String month = dtok.nextToken();
String day = dtok.nextToken();
int m = Integer.parseInt(month);
return m;
}
}
return -1;
}
public String getIP(String line) {
StringTokenizer tok = new StringTokenizer(line);
if (tok.countTokens() == 4) {
String ip = tok.nextToken();
String date = tok.nextToken();
String hour = tok.nextToken();
String page = tok.nextToken();
StringTokenizer dtok = new StringTokenizer(date, "-");
return ip;
}
return null;
}
public String getPage(String line) {
StringTokenizer tok = new StringTokenizer(line);
if (tok.countTokens() == 4) {
String ip = tok.nextToken();
String date = tok.nextToken();
String hour = tok.nextToken();
String page = tok.nextToken();
StringTokenizer dtok = new StringTokenizer(date, "-");
return page;
}
return null;
}
public void visitsPerMonth() {
String line = null;
do {
line = nextLine();
if (line != null) {
int m = getMonth(line);
if (m != -1) {
months[m - 1]++;
}
}
} while (line != null);
// Print the result
String[] monthName = {"JAN ", "FEB ", "MAR ",
"APR ", "MAY ", "JUN ", "JUL ", "AUG ", "SEP ",
"OCT ", "NOV ", "DEC "};
for (int i = 0; i < 12; i++) {
System.out.println(monthName[i] + months[i]);
}
}
public int count() throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream("webserver.log"));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
}
return count;
} finally {
is.close();
}
}
public void UniqueIP() throws IOException{
String line = null;
for (int x = 0; x <count(); x++){
line = nextLine();
if (line != null) {
if(hm1.containsKey(getIP(line)) == false) {
hm1.put(getIP(line), 1);
} else {
hm1.put(getIP(line), hm1.get(getIP(line)) +1 );
}
}
}
Set set = hm1.entrySet();
Iterator i = set.iterator();
System.out.println("\nNumber of unique visitors: " + hm1.size());
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + " - ");
System.out.println(me.getValue() + " visits");
}
}
public void pageVisits() throws IOException{
String line = null;
for (int x = 0; x <count(); x++){
line = nextLine();
if (line != null) {
if(hm2.containsKey(getPage(line)) == false)
hm2.put(getPage(line), 1);
else
hm2.put(getPage(line), hm2.get(getPage(line)) +1 );
}
}
Set set = hm2.entrySet();
Iterator i = set.iterator();
System.out.println("\nNumber of pages visited: " + hm2.size());
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + " - ");
System.out.println(me.getValue() + " visits");
}
}
Any help figuring out the problem would be much appreciated as I am quite stuck.
I didn't read the code thoroughly yet, but I guess you're not setting the read position back to the beginning of the file when you start a new operation. Thus nextLine() would return null.
You should create a new Scanner for each operation and close it afterwards. AFAIK scanner doesn't provide a method to go back to the first byte.
Currently I could also think of 3 alternatives:
Use a BufferedReader and call reset() for each new operation. This should cause the reader to go back to byte 0 provided you didn't call mark() somewhere.
Read the file contents once and iterate over the lines in memory, i.e. put all lines into a List<String> and then start at each line.
Read the file once, parse each line and construct an apropriate data structure that contains the data you need. For example, you could use a TreeMap<Date, Map<Page, Map<IPAdress, List<Visit>>>>, i.e. you'd store the visits per ip address per page for each date. You could then select the appropriate submaps by date, page and ip address.
The reset method of BufferedReader that Thomas recommended would only work if the file size is smaller than the buffer size or if you called mark with a large enough read ahead limit.
I would recommend reading throught the file once and to update your maps and month array for each line. BTW, you don't need a Scanner just to read lines, BufferedReader has a readLine method itself.
BufferedReader br = ...;
String line;
while (null != (line = br.readLine())) {
String ip = getIP(line);
String page = getPage(line);
int month = getMonth(line);
// update hashmaps and arrays
}