Create file name using date and time

后端 未结 5 1810
清酒与你
清酒与你 2020-12-14 00:31

I hope you could help me, I\'m trying to call in the date from another class and looks like \"2011-03-09 06-57-40\", I want to use this to create the file below but everytim

5条回答
  •  天涯浪人
    2020-12-14 01:12

    I'll try and answer all the same. To obtain a date or time string in the most controlled manner possible use the following code

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String dateStr = dateFormat.format(cal.getTime());
    

    Look up http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html . It might help with understanding. You can also add hour/minute or what you need to the formatted String.

    Another option might be to always set the "lower" fields like milliseconds, seconds, minutes in the Calendar to zero.

    cal.set(Calendar.MINUTE,0);
    

    If you are retrieving your date from another class and cannot directly create a calendar you can also put the date into the calendar (note: for just formatting you don't need the calendar)

    cal.setTime(date);
    

    Maybe this helps getting more control of the created filename / file.

提交回复
热议问题