如何在JAVA代码中添加时间戳,就像计数一样(每行一个)?

huangapple go评论66阅读模式
英文:

How to add Timestamp in JAVA code like count (in each line)

问题

I have a java code which takes data from CSV file and shows as html in tabular form.

我有一个Java代码,它从CSV文件中获取数据,并以表格形式显示为HTML。

I want to add timestamp should appear automatically like count appears at the start of each row.

我想要添加时间戳,就像计数在每一行的开头一样自动显示。

It has three JAVA files which I have pasted below all together.

它有三个Java文件,我已经一起粘贴在下面。

Please advise what code shall I add and where exactly to fulfill the timestamp requirement.

请告诉我应该添加什么代码,以及在哪里精确添加以满足时间戳的要求。

Below is the code example:

以下是代码示例:

package display;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Play {
    public static List<LineInfo> INFO = new ArrayList<LineInfo>();

    // ...

    public static void loadInfo() throws IOException {
        int count = 0;

        String filePath = "C:\\folder\\";
        String fileName = "file.csv";
        BufferedReader csvReader = new BufferedReader(new FileReader(filePath + fileName));
        String row = "";

        while ((row = csvReader.readLine()) != null) {
            count++;
            // Add timestamp here
            String timestamp = getCurrentTimestamp(); // Replace this with your timestamp logic
            String[] raw = row.split(",");
            // ...

            LineInfo line = new LineInfo(count, timestamp, data[0], data[1], data[2], data[3], data[4]);
            INFO.add(line);
        }

        csvReader.close();
        System.out.println("File loaded successfully total records: " + (INFO.size() - 1));
    }

    // ...

    public static void main(String[] args) throws IOException, InterruptedException {
        // ...
    }
}

In the loadInfo method, I added a comment "// Add timestamp here" to indicate where you should add the timestamp. You should replace the getCurrentTimestamp() call with your logic to get the current timestamp and format it as needed.

loadInfo方法中,我添加了一个注释“//在这里添加时间戳”,以指示您应该在何处添加时间戳。您应该用获取当前时间戳并按需要格式化的逻辑替换getCurrentTimestamp()调用。

英文:

I have a java code which takes data from CSV file and shows as html in tabular form.

I want to add timestamp should appear automatically like count appears at start of each row.

It have three JAVA files which I have pasted below all together.

Please advice what code shall I add and where exactly to fulfill timestamp requirement.

Below is the code example:

package display;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class Play 
{
public static List &lt;LineInfo&gt; INFO = new ArrayList&lt;LineInfo&gt;();
///////////////////////////////////////////////////////////////////////////////////////////
public static void loadInfo() throws IOException
{
int count = 0;
String filePath = &quot;C:\\folder\\&quot;;
String fileName = &quot;file.csv&quot;;
BufferedReader csvReader = new BufferedReader(new FileReader(filePath + fileName));
String row = &quot;&quot;;
/////////////////////////////////////////////////////////////////////////////////
while ((row = csvReader.readLine()) != null)
{
count++;
String[] raw = row.split(&quot;,&quot;);
//System.out.println(row);
String[] data = new String[20];
for (int i = 0; i &lt; raw.length; i++) 
{
data[i] = raw[i];
}
for (int i = 0; i &lt; data.length; i++) 
{
if(data[i] == null)
data[i] = &quot;&quot;;
}
LineInfo line = new LineInfo(count, data[0], data[1], data[2], data[3], data[4]);
INFO.add(line);
}
//////////////////////////////////////////////////////////////////////////////
csvReader.close();
System.out.println(&quot;File loaded successfully total records : &quot; + (INFO.size() -1));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void htmlIT() throws IOException 
{
HTMLify html = new HTMLify(INFO);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException, InterruptedException
{
int i = 0;
while (i &lt; 1)
{
loadInfo();
htmlIT();
INFO.clear();
//wait
TimeUnit.SECONDS.sleep(300);
}
}
}
----------------------------------------------------
package display;
/////////////////////////////////////////////////////////////////////////////////////////////////////
import java.io.IOException;
public class LineInfo {
int seq = 0; // system sequence number
String ser = &quot;&quot;; //
String subject = &quot;&quot;; //
String title1 = &quot;&quot;; //
String title2 = &quot;&quot;; //
String title3 = &quot;&quot;; // 
//////////////////////////////////////////////////////////////////////////////////////////////////////
public LineInfo(int sn, String sr, String sbj, String t1, String t2, String t3) throws IOException
{
this.seq = sn;				
this.ser = sr;			
this.subject = sbj;		
this.title1 = t1;
this.title2 = t2;
this.title3 = t3;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
}
-------------------------------------------------------
package display;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class HTMLify 
{
public static List &lt;LineInfo&gt; INFO = new ArrayList&lt;LineInfo&gt;();
public static List &lt;String&gt; SUBJECT = new ArrayList&lt;String&gt;();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void ddHTML() throws IOException
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
StringBuilder htmlDD = new StringBuilder();
htmlDD.append(&quot;&lt;html&gt;&lt;head&gt;&lt;meta http-equiv=\&quot;refresh\&quot; content=\&quot;30\&quot;/&gt;&lt;title&gt; SHEET &lt;/title&gt;&quot;);
htmlDD.append(&quot;&lt;body bgcolor=\&quot;#ffffff\&quot;&gt;&quot;);
//Report style
htmlDD.append(&quot;&lt;style type=\&quot;text/css\&quot;&gt;&quot;);
htmlDD.append(&quot;.tg  {border-collapse:collapse;border-spacing:0;}&quot;);
htmlDD.append(&quot;.tg td{font-family:Arial, sans-serif;font-size:22px;padding:10px 5px;border-style:0;border-width:0px;overflow:hidden;word-break:normal;}&quot;);
htmlDD.append(&quot;.tg th{font-family:Arial, sans-serif;font-size:22px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}&quot;);
htmlDD.append(&quot;.tg .tg-smpa{font-weight:bold;font-size:40px;bold;background-color:#e8e8e8;color:#000000;text-align:center}&quot;);
htmlDD.append(&quot;.tg .tg-w672{font-weight:bold;font-size:22px;background-color:#5B5B5B;color:#ffffff;text-align:center;text-align:center;vertical-align:top}&quot;);
htmlDD.append(&quot;.tg .tg-jmap{font-weight:bold;font-size:22px;text-shadow: rgba(245,245,245,0.5) 1px 2px 1px;background-color:#000000;text-align:center;color:#ffffff;text-align:center;vertical-align:center}&quot;);
htmlDD.append(&quot;.tg .tg-cgn1{background-color:#FFFFFF;text-align:center;color:#585858;vertical-align:center}&quot;);
htmlDD.append(&quot;&lt;/style&gt;&quot;);
htmlDD.append(&quot;&lt;/head&gt;&quot;);
htmlDD.append(&quot;&lt;table align=\&quot;center\&quot; class=\&quot;tg\&quot;&gt;&quot;);
htmlDD.append(&quot;&lt;center&gt;&lt;tr&gt;&lt;td class=\&quot;tg-smpa\&quot; colspan=\&quot;13\&quot;&gt;&lt;img src=\&quot;\\4FW\\images\\header.png\&quot; style=\&quot;float:center;\&quot;&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/center&gt;&quot;);
for (int i = 0; i &lt; SUBJECT.size(); i++)
{
int count = 0;
htmlDD.append(&quot;&lt;center&gt;&lt;tr&gt;&lt;th class=\&quot;tg-smpa\&quot; colspan=\&quot;7\&quot;&gt;&quot; + SUBJECT.get(i) + &quot;&lt;/th&gt;&lt;/tr&gt;&lt;/center&gt;&quot;);
htmlDD.append(&quot;&lt;tr&gt;&lt;td class=\&quot;tg-jmap\&quot;&gt;&quot; + INFO.get(0).ser + &quot;&lt;/td&gt;&lt;td class=\&quot;tg-jmap\&quot;&gt;&quot; + INFO.get(0).title1 + &quot;&lt;/td&gt;&lt;td class=\&quot;tg-jmap\&quot;&gt;&quot; + INFO.get(0).title2 + &quot;&lt;/td&gt;&lt;td class=\&quot;tg-jmap\&quot;&gt;&quot; + INFO.get(0).title3 + &quot; &lt;/td&gt;&lt;/tr&gt;&quot;);
for (int z = 1; z &lt; INFO.size(); z++)
{
if(SUBJECT.get(i).equals(INFO.get(z).subject))
{
count++;
htmlDD.append(&quot;&lt;tr&gt;&lt;td class=\&quot;tg-cgn1\&quot;&gt;&quot; + count + 
&quot;&lt;/td&gt;&lt;td class=\&quot;tg-cgn1\&quot;&gt;&quot; +&quot;&lt;img src=\&quot;\\folder\\images\\Alerts\\&quot; + INFO.get(z).title1 + &quot;.gif\&quot; style=\&quot;float:center;\&quot;&gt;&quot; +
&quot;&lt;/td&gt;&lt;td class=\&quot;tg-cgn1\&quot;&gt;&quot; + INFO.get(z).title2 + 
&quot;&lt;/td&gt;&lt;td class=\&quot;tg-cgn1\&quot;&gt;&quot; + INFO.get(z).title3 +
&quot;&lt;/td&gt;&lt;/tr&gt;&quot;);
}
}
htmlDD.append(&quot;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);
}
//htmlDD.append(&quot;&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&quot;);
htmlDD.append(&quot;&lt;center&gt;&lt;tr&gt;&lt;td class=\&quot;tg-smpa\&quot; colspan=\&quot;7\&quot;&gt;&lt;img src=\&quot;\\4FW\\images\\footer.png\&quot; style=\&quot;float:center;\&quot;&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/center&gt;&quot;);
htmlDD.append(&quot;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;&quot;);
File saveLocal = new File(&quot;C:\\xampp\\htdocs\\newfolder\\index.html&quot;);
BufferedWriter writer = new BufferedWriter(new FileWriter(saveLocal));
writer.write(htmlDD.toString());
writer.close();
System.out.println(&quot;Display file generated.&quot;);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public HTMLify (List &lt;LineInfo&gt; info) throws IOException
{
this.INFO = info;
List &lt;String&gt; subj = new ArrayList&lt;String&gt;();
for (int i =1; i &lt; info.size(); i++)
{
String sbj = info.get(i).subject;
subj.add(sbj);
}
SUBJECT = subj.stream().distinct().collect(Collectors.toList()); 
ddHTML();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}

Thanks in advance.

答案1

得分: 1

你可以按以下方式操作:

htmlDD.append("&lt;tr&gt;&lt;td&gt;" + System.currentTimeMillis() + "&lt;/td&gt;&lt;td class=\&quot;tg-cgn1\&quot;&gt;" + count + 
                            "&lt;/td&gt;....

请确保为时间戳添加标题列(即&lt;th&gt;Timestamp&lt;/th&gt;),否则表格将会显示失真。

更新

(回答评论中的进一步问题)

> 它显示为14位连续数字的毫秒。我如何将其转换为像yyyy-mm-dd hh:mm这样的格式。

您可以使用DateTimeFormatter将其转换为任何您喜欢的格式,但我认为您只是想显示日期时间的所有部分(年、月、日、小时、分钟、秒、纳秒),因此,您可以简单地将System.currentTimeMillis()替换为Instant.now()

> 我只想为新行生成新的时间戳,以前添加的行应该在将该行添加到CSV文件时具有固定的时间戳。但是,目前当我在添加新行后保存CSV文件并运行程序时,它会将所有行的时间更改为当前时间。有可能吗?

这不是什么大问题。为了做到这一点,您可以在此程序的一部分中而不是生成时间戳时,将Instant.now()的值存储在某个文件或数据库中,然后在此程序中获取相同的值。

英文:

You can do it as follows:

htmlDD.append(&quot;&lt;tr&gt;&lt;td&gt;&quot; + System.currentTimeMillis() + &quot;&lt;/td&gt;&lt;td class=\&quot;tg-cgn1\&quot;&gt;&quot; + count + 
&quot;&lt;/td&gt;....

Make sure to add the heading column for the timestamp (i.e. &lt;th&gt;Timestamp&lt;/th&gt;) otherwise, the table will appear distorted.

Update

(to answer further questions from the comment)

> It appeared as milli sec as 14 digit continues number. How can I
> convert it in format like yyyy-mm-dd hh:mm.

You can convert to whatever format you like using DateTimeFormatter but I think all you want is to display all parts (year, month, day, hour, minute, second, nanosecond) of the date-time and therefore, you can simply replace System.currentTimeMillis() with Instant.now().

> I want new timestamp for new row only and previously added row should
> have fixed timestamp at the time when that row added in CSV file. But
> as of now when I save CSV file after adding new row and run program.
> It changes time for all rows to current time. Is it possible?

It is not a big deal. In order to do it, instead of generating the timestamp as part of this program, you can store the value of Instant.now() in some file or database and then fetch the same in this program.

huangapple
  • 本文由 发表于 2020年8月9日 16:01:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63323926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定