Merge branch 'master' of https://github.uci.edu/rtrimana/smart_home_traffic
[pingpong.git] / Code / Projects / DateWriter / DateWriter.java
1 import java.io.File;
2 import java.io.BufferedReader;
3 import java.io.FileReader;
4 import java.io.PrintWriter;
5 import java.time.LocalDate;
6 import java.time.LocalTime;
7 import java.time.format.DateTimeFormatter;
8 import java.io.IOException;
9
10 public class DateWriter {
11
12         public static void main(String[] args) throws IOException {
13                 if (args.length < 3) {
14                         System.out.println("Usage: java " + DateWriter.class.getSimpleName() + " /path/to/file/with/timestamps /path/to/new/timestamp/file/with/dates initial_date_in_MM/dd/uuuu_format");
15                         System.exit(1);
16                 }
17                 String pathOriginal = args[0];
18                 String pathModified = args[1];
19                 String initialDateStr = args[2];
20                 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
21                 LocalDate date = LocalDate.parse(initialDateStr, dateFormatter);
22                 File originalFile = new File(pathOriginal);
23                 // Create output file
24                 File modifiedFile = new File(pathModified);
25                 modifiedFile.createNewFile();
26                 BufferedReader reader = new BufferedReader(new FileReader(originalFile));
27                 PrintWriter writer = new PrintWriter(modifiedFile);
28                 String line = null;
29                 String prevLine = null;
30                 while ((line = reader.readLine()) != null) {
31                         if (isNewDay(line, prevLine)) {
32                                 // Advance date
33                                 date = date.plusDays(1);
34                         }
35                         writer.println(String.format("%s %s", date.format(dateFormatter), line));
36                         prevLine = line;
37                 }
38                 writer.flush();
39                 writer.close();
40                 reader.close();
41         }
42
43         private static boolean isNewDay(String line, String prevLine) {
44                 if (prevLine == null) {
45                         return false;
46                 }
47                 // First part handles case where we pass midnight and the following timestamp is an AM timestamp
48                 // Second case handles case where we pass midnight, but the following timestamp is a PM timestamp
49                 return line.endsWith("AM") && prevLine.endsWith("PM") || toLocalTime(line).isBefore(toLocalTime(prevLine));
50         }
51
52         private static LocalTime toLocalTime(String timeString) {
53                 return LocalTime.parse(timeString, DateTimeFormatter.ofPattern("h:mm:ss a"));
54         }
55 }