0

I'm fetching from an API a date string that is formatted like this : DD_MM_YYYY_hh_mm__ss

I want to display the string in this format : DD/MM/YYYY hh:mm:ss

How can I achieve that ?

3 Answers 3

4

You can replace the underscore sequences with the appropriate characters based on their position within the input string:

function convertDate(date) {
    return date.replace(/_+/g, (_, n) => (n < 10) ? "/" : (n > 10) ? ":" : " ");
}

console.log(convertDate("DD_MM_YYYY_hh_mm__ss"));

Or slightly simpler:

function convertDate(date) {
    let n = 0; return date.replace(/_+/g, () => "// ::"[n++]);
}

console.log(convertDate("DD_MM_YYYY_hh_mm__ss"));

Sign up to request clarification or add additional context in comments.

Comments

3

One way:

const str = '18_03_2022_12_21_34'
// to string
const res = str.split('_')
const r = res.slice(0, 3).join('/') + ' ' + res.slice(-3).join(':')
console.log(r)
// or to date
console.log(new Date(res.slice(0, 3).join('/').split('/').reverse().join('/') + ' ' + res.slice(-3).join(':')))

Comments

2

Vue Filter

Code:

Vue.filter('stringTodateTime', function ( dateTimeString ) {
    if (!dateTimeString) return ''
    return dateTimeString.replace(/_+/g, (_, n) => (n < 10) ? "/" : (n > 10) ? ":" : " ");
})

Usage:

{{ 12_04_2021_12_59_34 | stringTodateTime }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.