I am trying to write a simple script that convert the first field of a line in universal time.
import java.util.*;
import java.text.*;
import java.io.*;
public class StringToDate {
public static void main(String[] argv) {
if (argv.length != 1) {
System.err.println("Usage: java StringToDate file.in");
System.exit(1);
}
try {
FileInputStream fstream = new FileInputStream(argv[1]);
String delims = "[,]+";
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(delims);
DateFormat formatter ;
long epoch = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(tokens[0]).getTime();
System.out.println(String.valueOf(epoch)+',' +tokens[1]+'\n');
}
//Close the input stream
in.close();
}
catch (Exception e){System.err.println("Error: " + e.getMessage());}
}
}
the file is in the form:
2012-02-12 17:00:00,(Sun) Kardemir Karabukspor v Fenerbahce
two questions:
1) why this code is unable open the file when i put argv[1] as argument?
2) why the universal time is a completely wrong number? i.e. the output is
1329062400000,(Sun) Kardemir Karabukspor v Fenerbahce
namely the universaletime is three 0’s longer (actually has to be 1329062400).
1) You’ve ensured your array only has a single item, so it’s
argv[0], notargv[1]. Arrays always start at element 0 in Java.2)
Date.getTime()returns milliseconds since the epoch, not seconds. If you want seconds, divide by 1000. The value looks fine to me, when viewed as milliseconds…