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) {}
Author by
Morten Hagh
Updated on June 04, 2022Comments
-
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 over 12 yearsThat'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 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 over 12 yearsI just copy and paste the code which I was using in one application, that's why
-
Caner over 12 yearsok, but still
dateFormat
is not used anywhere so could be removed.And why did you give me -1? -
Raghav Chopra over 12 yearsi have clearly mentioned above that this is to get the cureent not to save in the file@LAS_VEGAS
-
Morten Hagh over 12 yearsIf 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 over 12 yearsThen add
import java.util.Date;
-
Caner over 12 yearsok, 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 over 12 yearsI 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 over 12 yearssorry 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 about 9 yearsYou 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);