Pick day, month and year out file.lastModified();

你。 提交于 2019-12-11 07:56:08

问题


I know how to use file.lastModified();. When I println that I get (for example): Sat Mar 17 09:24:33 GMT+01:00 2012. But is it possible that I only get the day, month and year as numbers, for example: 17 03 2012

Is their a way to do this, maybe a filter, or an other function to get last modified date in numbers?


回答1:


You can use SimpleDateFormat class, i.e.

package com.example.file;

import java.io.File;
import java.text.SimpleDateFormat;

public class GetFileLastModifiedExample
{
    public static void main(String[] args)
    {   
    File file = new File("\\somefile.txt");

    System.out.println("Before Format : " + file.lastModified());

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    System.out.println("After Format : " + sdf.format(file.lastModified()));
    }
}



回答2:


is file a java.io.File object?

lastModified should return time in milliseconds. You can create a Date object with the lastModified return value and the format the output with a SimpleDateFormat

    Date date = new Date(file.lastModified());
    System.out.println(date);

    SimpleDateFormat sdf = new SimpleDateFormat("d M y");
    System.out.println(sdf.format(date));



回答3:


Try this,

long longDate = file.lastModified();        
Date date = new Date(longDate);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String newDate = formatter.format(date);
System.out.println("Formatted date " + newDate);



回答4:


according to the documentation

File.lastModifed()

should return a long value representing the time the file was last modified, measured in milliseconds since the epoch. Yon can use the long value in conjunction with Calendar

    Calendar rightNow = Calendar.getInstance()
    rightNow.setTimeInMillis(longValue)

and use rightNow.get(...)

to retrive day, month and year



来源:https://stackoverflow.com/questions/9818813/pick-day-month-and-year-out-file-lastmodified

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