Current timestamp as filename in Java

限于喜欢 提交于 2020-01-01 00:57:15

问题


I want to name new files created by my Java application with the current timestamp.

I need help with this. How do I name the new files created with the current timestamp? Which classes should I include?


回答1:


No need to get too complicated, try this one liner:

String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());



回答2:


try this one

String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());



回答3:


You can get the current timestamp appended with a file extension in the following way:

String fileName = new Date().getTime() + ".txt";



回答4:


Use SimpleDateFormat as aix suggested to format the current time into a string. You should use a format that does not include / characters etc. I would suggest something like yyyyMMddhhmm




回答5:


You can use DateTime

import org.joda.time.DateTime

Option 1 : with yyyyMMddHHmmss

DateTime.now().toString("yyyyMMddHHmmss")

Will give 20190205214430

Option 2 : yyyy-dd-M--HH-mm-ss

   DateTime.now().toString("yyyy-dd-M--HH-mm-ss")

will give 2019-05-2--21-43-32




回答6:


Date, SimpleDateFormat and whatever classes are required on the I/O side of things (there are many possibilities).



来源:https://stackoverflow.com/questions/7488559/current-timestamp-as-filename-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!