Saving image to sd with current date and time in name doesn't work

11,891

Solution 1

Colon : is not a valid character in a file name, that is why it is failing to create such a file. Try change your name pattern to something like this:

CharSequence s  = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());

Solution 2

Put this code and try:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());

Solution 3

Here is an alternate solution:

File cameraFolder;

if (android.os.Environment.getExternalStorageState().equals
        (android.os.Environment.MEDIA_MOUNTED))
    cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(),
            "YOUR_FOLDER_NAME/");
else
    cameraFolder= StatusUpdate.this.getCacheDir();
if(!cameraFolder.exists())
    cameraFolder.mkdirs();

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
String imageFileName = "picture_" + timeStamp + ".jpg";

File photo = new File(Environment.getExternalStorageDirectory(), 
        "YOUR_FOLDER_NAME/" + imageFileName);

If you want just the TimeStamp as the image name, you can remove "picture_" + from the String imageFileName.

Share:
11,891
3Gee
Author by

3Gee

I like FE and BE development and am particularly passionate about UI&UX design.

Updated on June 25, 2022

Comments

  • 3Gee
    3Gee almost 2 years

    In my application I use a button to launch Camera application and save picture to specific folder on sdCard naming it by current date and time. When I hardcode the name for the picture, it works fine, but if I'm trying to put date in the name it doesn't work at all.

     Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
     File imagesFolder = new File(Environment.getExternalStorageDirectory(), Constants.IMAGE_FOLDER_URI);
     imagesFolder.mkdirs();    
     Date d = new Date();
     CharSequence s  = DateFormat.format("MM-dd-yy hh:mm:ss", d.getTime());    
     File image = new File(imagesFolder, s.toString() + ".jpg"); //this line doesn't work
    
     Uri uriSavedImage = Uri.fromFile(image);
     imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
     startActivity(imageIntent);
    

    If I put:

    s = "some_name";
    

    then it works, but I need current date and time in image name.