Android get date and insert to filename

14,806

You can use this:

import java.text.SimpleDateFormat;
// ...

SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);
Date now = new Date();
String fileName = formatter.format(now) + ".tar.gz";

Also you must be getting an error somewhere, that would help a lot to find the problem. Make sure you don't have empty catch blocks :

catch (Exception e) {}
Share:
14,806
Morten Hagh
Author by

Morten Hagh

Updated on June 04, 2022

Comments

  • Morten Hagh
    Morten Hagh almost 2 years

    I am having a quite annoying problem. I want to get the current date/time and insert it into a filename but I can't for my life get it to work.

    I want to get the time as 2011-11-18 12:13:57 and then insert it into my filename

    filename-2011-11-18-12:13:57.tar.gz

    I have tried SimpleDateFormat etc. but it just won't work!

    (I am writing in Eclipse Indigo)

  • Caner
    Caner over 12 years
    That's a terrible way to get the current date. There are already Java functions for this purpose. Plus the problem the poster is facing is not getting the date, but creating the file.
  • Caner
    Caner over 12 years
    -1 dateformat is created but not used anywhere? Also why woudl you copy a string to another string for no purpose?: String lastSyncTime = timeStamp;
  • Android-Droid
    Android-Droid over 12 years
    I just copy and paste the code which I was using in one application, that's why
  • Caner
    Caner over 12 years
    ok, but still dateFormat is not used anywhere so could be removed.And why did you give me -1?
  • Raghav Chopra
    Raghav Chopra over 12 years
    i have clearly mentioned above that this is to get the cureent not to save in the file@LAS_VEGAS
  • Morten Hagh
    Morten Hagh over 12 years
    If I use this one Eclipse tells me that date() is undefined and I need arguments to match it... I can get it to print the date but the date is 01_01_1970
  • Caner
    Caner over 12 years
    Then add import java.util.Date;
  • Caner
    Caner over 12 years
    ok, but now the date he will get will still be like 2011-11-18 12:13:57 and it doesn't work for him.(see comments under question)
  • Morten Hagh
    Morten Hagh over 12 years
    I cannot believe that this was the simple solution! I have been messing with this for 2 days! I cannot thank you enough! :) Eclipse have automatically imported everything else, but not this one! Thank you!
  • Caner
    Caner over 12 years
    sorry my bad, but I think this is still a very bad way to get current date. Because you can get the current date as string with couple of lines of code. Your logic might have some bug somewhere where it would be difficult to spot.
  • Pooks
    Pooks about 9 years
    You can get rid of the warning in Eclipse for SimpleDateFormat by specifying a known safe Locale. For example SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);