Reputation: 61
I'd like to have a piece of js that will automatically translate a given date format to different date formats.
In my Database I have all dates formatted as such: ex. 1941-10-30 08:00:00
I would like the code to pick the dates out of that string and convert them to 30.10.1941 and separate the time stamp.
Can I get some pointers to get me going? I am a relatively new coder with js
Thanks in advance
Upvotes: 0
Views: 3953
Reputation: 7881
Here is what I came up with when I needed to convert mm/dd/yyyy to verity of different formats. e.g dd/mm/yyyy, yyyy/mm/dd, yyyy-mm-dd, dd.mm.yyyy (it typescript, though just remove type hinting and you'll get vanilla js)
const dateStringToFormat = (dateString: string, format: string): string => {
const parts = dateString.split('/'); // assume incoming date format is mm/dd/yyyy
const date = new Date(Date.UTC(+parts[2], +parts[0]-1, +parts[1]));
let delimiter = '.';
if (format.includes('/')) {
delimiter = '/'
} else if (format.includes('-')) {
delimiter = '-';
}
const year = date.getFullYear();
const month = (date.getMonth() + 1 + '').padStart(2, '0');
const day = (date.getDate() + '').padStart(2, '0');
const position = (idx:number) => idx === 0 ? 0 : (idx < 6 ? 1 : 2);
const partsForamtted = [];
partsForamtted[position(format.indexOf('yyyy'))] = year;
partsForamtted[position(format.indexOf('mm'))] = month;
partsForamtted[position(format.indexOf('dd'))] = day;
return partsForamtted.join(delimiter);
}
Use like this:
dateStringToFormat('03/24/2021', 'dd-mm-yyyy') //24-03-2021
And here is unit tests for the function:
describe('test dateStringToFormat function', () => {
// incoming format is mm/dd/yyyy
test('Test formats with different delimeters, month followed by date and by year', () => {
expect(dateStringToFormat('03/24/2021', 'mm/dd/yyyy')).toBe('03/24/2021');
expect(dateStringToFormat('03/24/2021', 'mm.dd.yyyy')).toBe('03.24.2021');
expect(dateStringToFormat('03/24/2021', 'mm-dd-yyyy')).toBe('03-24-2021');
expect(dateStringToFormat('12/05/2021', 'mm-dd-yyyy')).toBe('12-05-2021');
})
test('Test formats with different delimeters, year followed by month and by date', () => {
expect(dateStringToFormat('03/24/2021', 'yyyy/mm/dd')).toBe('2021/03/24');
expect(dateStringToFormat('03/24/2021', 'yyyy.mm.dd')).toBe('2021.03.24');
expect(dateStringToFormat('03/24/2021', 'yyyy-mm-dd')).toBe('2021-03-24');
expect(dateStringToFormat('12/05/2021', 'yyyy-mm-dd')).toBe('2021-12-05');
})
test('Test formats with different delimeters, date followed by month and by year', () => {
expect(dateStringToFormat('03/24/2021', 'dd/mm/yyyy')).toBe('24/03/2021');
expect(dateStringToFormat('03/24/2021', 'dd.mm.yyyy')).toBe('24.03.2021');
expect(dateStringToFormat('03/24/2021', 'dd-mm-yyyy')).toBe('24-03-2021');
expect(dateStringToFormat('12/05/2021', 'dd-mm-yyyy')).toBe('05-12-2021');
})
})
Upvotes: 0
Reputation: 81
Assuming the input format won't change and you want a very simple solution with no external libraries, you can do the following:
yourDate = new Date('1941-10-30 08:00:00'); // Convert to JS Date
// Method 1
formattedDateString = yourDate.getDate()+'.'+(yourDate.getMonth()+1)+'.'+yourDate.getFullYear(); // Format to the desired date format, Method 1
// Method 2
formattedDateString2 = yourDate.toLocaleString('en-gb', { day: '2-digit', month: 'numeric',year: 'numeric' });
formattedDateString2 = formattedDateString2.replace(/\//g, '.'); // remove space and comma
// See the output
console.log(formattedDateString); // Method 1
console.log(formattedDateString2); // Method 2
Upvotes: 1
Reputation: 38209
You can parse your time string like that:
const str = `1941-10-30 08:00:00`;
const [y, m, d] = str.split(/[ -]+/);
const [h, mi, s] = str.split(/[ ]+/)[1].split(/[:]+/);
const mydate = new Date(y, m, d, null, h, mi, s);
const formattedDate = `${d}.${m}.${y}`;
console.log(`my date: `, formattedDate);
console.log(mydate.toTimeString());
Try to avoid using Date
contructors and Date.parse()
methods as some incorrect parsing results can be given.
Upvotes: 0
Reputation: 191
I recommend to you to use Moment.js, it is very simple and useful for any operations regarding timestamps.
just you can use moment('YOUR_TIME_STAMP').format('YYYY-MM-DD HH:MM:SS)
Upvotes: 1
Reputation: 3153
this is normal date format returned by new Date()
2002-12-09T00:00:00.000Z
and to convert it to only MM/DD/YYYY
you can do:
const date = new Date("2002-12-09T00:00:00.000Z").toLocaleDateString();
and to convert it to time:
const date = new Date("2002-12-09T00:00:00.000Z").toLocaleTimeString();
Upvotes: 1