adde143215d335dc182cd977ade6221eb1695a16
[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 /path/to/file/with/timestamps /path/to/new/timestamp/file/with/dates initial_date_in_uuuu-MM-dd_format");
15                         System.exit(1);
16                 }
17                 String pathOriginal = args[0];
18                 String pathModified = args[1];
19                 String initialDateStr = args[2];
20                 LocalDate date = LocalDate.parse(initialDateStr, DateTimeFormatter.ofPattern("uuuu-MM-dd"));
21                 File originalFile = new File(pathOriginal);
22                 // Create output file
23                 File modifiedFile = new File(pathModified);
24                 modifiedFile.createNewFile();
25                 BufferedReader reader = new BufferedReader(new FileReader(originalFile));
26                 PrintWriter writer = new PrintWriter(modifiedFile);
27                 String line = null;
28                 String prevLine = null;
29                 while ((line = reader.readLine()) != null) {
30                         if (isNewDay(line, prevLine)) {
31                                 // Advance date
32                                 date = date.plusDays(1);
33                         }
34                         writer.println(String.format("%s %s", date.toString(), line));
35                         prevLine = line;
36                 }
37                 writer.flush();
38                 writer.close();
39                 reader.close();
40         }
41
42         private static boolean isNewDay(String line, String prevLine) {
43                 if (prevLine == null) {
44                         return false;
45                 }
46                 // First part handles case where we pass midnight and the following timestamp is an AM timestamp
47                 // Second case handles case where we pass midnight, but the following timestamp is a PM timestamp
48                 return line.endsWith("AM") && prevLine.endsWith("PM") || toLocalTime(line).isBefore(toLocalTime(prevLine));
49         }
50
51         private static LocalTime toLocalTime(String timeString) {
52                 return LocalTime.parse(timeString, DateTimeFormatter.ofPattern("h:mm:ss a"));
53         }
54 }