Change date in the file name

Advanced Renamer forum
#1 : 23/10-22 20:43
Nils
Nils
Posts: 3
In the past a named my files YearMonthDay e.g. 20221022_my house dog.
Now I would like to change the format how the date is written into 2022-10-22_my house dog.
With which method can I automatically change the file name?
And how can I do it, when I have the date at the end of the file name: My house dog_20221022?


23/10-22 20:43
#2 : 28/10-22 20:34
Daniel Gruner
Daniel Gruner
Posts: 5
Reply to #1:

Hi, here is the code. Just had a few minutes and had fun with it. There might be better solutions (with regex and so on) but this should help.

Important is that you have files with YYYYMMDD_ at the beginning or _YYYYMMDD at the end of the file (as you described in your post).

var fileName = item.name;

var tryDateBefore = parseInt(fileName.substr(0, 8));
var tryDateBehind = parseInt(fileName.substr(fileName.length - 8, 8));

var date;
var restOfFileName;

if (!isNaN(tryDateBefore)) {
date = tryDateBefore; // 20221022
restOfFileName = fileName.substr(9, fileName.length - 9); // my house dog
} else if (!isNaN(tryDateBehind)) {
date = tryDateBehind; // 20221022
restOfFileName = fileName.substr(0, fileName.length - 9); // my house dog
}
var year = date.toString().substr(0, 4); // 2022
var month = date.toString().substr(4, 2); // 10
var day = date.toString().substr(6, 2); // 22
return year + "-" + month + "-" + day + "_" + restOfFileName;


28/10-22 20:34
#3 : 30/10-22 19:37
Nils
Nils
Posts: 3
Reply to #2:
Thank you very much for this code. I copied and tried it, but now it always puts the date at the beginning of the new file name.
Is it possible, when the date is at the end that also in the new file name the date is at the end?


30/10-22 19:37 - edited 30/10-22 19:56
#4 : 03/11-22 11:20
David Lee
David Lee
Posts: 1026
Reply to #3:
Much easier to use a Replace method with a regular expression!

Replace: (\d{4})(\d{2})(\d{2})
with: \1-\2-\3
Use regular expressions

This will convert an 8-digit string anywhere in the filename.

To convert a string only at the beginning use the regex: ^(\d{4})(\d{2})(\d{2})
and at the end: (\d{4})(\d{2})(\d{2})$

To convert either just use two Replace methods


03/11-22 11:20
#5 : 03/11-22 19:49
Nils
Nils
Posts: 3
Reply to #4:
Thank you! That works perfectely!


03/11-22 19:49