-2

I am new to javascript and trying to get parts of the string and format it.

I have a string:

update_time="THU 2017-06-29 23:41:13 ET"

I want to get and format the date to look like: 06/29/2017

Any help would be appreciated

AndroidDev21921
  • 695
  • 1
  • 8
  • 21
  • "How to format a date in Javascript" has been asked at least 4687167035 times on StackOverflow. A Google search would take you about 2 seconds. – Jeremy Thille Jul 01 '17 at 19:19
  • Yup, completely understand, i jsut didn't know how to get to the part of the string i wanted to format. – AndroidDev21921 Jul 01 '17 at 19:48
  • This has been asked [*many times before*](https://stackoverflow.com/search?q=%5Bjavascript%5D+reformat+date+string) – RobG Jul 01 '17 at 21:20

5 Answers5

1

You have a str.substr(Begin, Length) method in javascript. The following code will give you the right parts of the string.

update_time="THU 2017-06-29 23:41:13 ET"
new_format = update_time.substr(9,2) + '/' + update_time.substr(12,2) + '/' + update_time.substr(4,4)  

The result being a var new_format with the string 06/29/2017.

Pim
  • 850
  • 7
  • 17
1

You could use this regular expression. It detects anything formatted as yyyy-dd-mm and formats it as dd/mm/yyyy

new_time = update_time.replace(/.*(\d{4})-(\d{2})-(\d{2}).*/, "$2/$3/$1");

If you want to keep the original string in place, but just change the date, then remove the .* from both sides.

Khauri
  • 3,753
  • 1
  • 11
  • 19
0

best will be to split it with whitespace and then, take the second element and construct a date and use toLocaleDateString()

new Date(update_time.split(' ')[1]).toLocaleDateString()

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
  • 1
    Just a warning though, [toLocaleDateString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString) will change the representation based on the user's computer settings and other stuff, which can be be good. But if OP wants it too look consistent they can use `toLocaleDateString('en-US'). The only issue is that it's not zero padded in some cases either. So it's 6/29/2017 instead of 06/29/2017 – Khauri Jul 01 '17 at 19:36
  • yep, correct. so the target is to understand the string input as a date in the most possible shortest way, the center of gravity here is "Date". after that we can even manually prepare any kinda output even if no feature method is there. Thanks for your comment :) – Koushik Chatterjee Jul 01 '17 at 19:40
  • Please don't recommend parsing strings with the Date constructor. This string has an associated time and timezone, reducing it to just the date part and parsing it with the built-in parser means it will be treated as UTC (or perhaps local or invalid in some browsers). So it will appear to be a different date for hosts with a timezone offset west of Greenwich. – RobG Jul 01 '17 at 21:16
  • @KoushikChatterjee—options for *toLocaleString* are not supported by all browsers in use, so the result can be anything. – RobG Jul 01 '17 at 21:22
0
function getDateFormat(data){
    if (!data) return null;
    let dateObj = new Date(parseInt(data));
    let date = dateObj.getDate();
    let month = dateObj.getMonth();
    let year = dateObj.getFullYear();
    let time = dateObj.getHours();
    let minutes = dateObj.getMinutes();
    let seconds = dateObj.getSeconds();
    if (time > 12){
        time = time - 12;
        time = time + ':' + minutes + ':' + seconds + ' PM';
    }else{
        time = time + ':' + minutes + ':' + seconds + ' AM';
    }
    date = date + ' - ' + month + ' - ' + year;
    return {
        date: date,
        time: time
    }
}

This function not working in date string.

If you have date in milliseconds, you can use my method to get date and time properly.

Just pass milliseconds to my function it returns a object that contains date and time.

Vasi
  • 1,147
  • 9
  • 16
  • Given the input "THU 2017-06-29 23:41:13 ET", *parseInt* will return `NaN`, and `new Date(NaN)` will return an invalid date. – RobG Jul 01 '17 at 21:18
  • Your input is wrong. Only you can send numerical string to my function. " var data = new Date().getTime(); getDateFormat(data); " try this. – Vasi Jul 01 '17 at 21:23
  • The OP is trying to reformat a date string, not format a Date (and there are many, many duplicates for both). – RobG Jul 01 '17 at 21:24
  • Mentioned it to my answer. – Vasi Jul 01 '17 at 21:31
-1

You can use defaults JavaScript functions:

var update_time="THU 2017-06-29 23:41:13 ET"

Updates: As RobG explained we can't parse only with the Date object. So we can either use the regular expression or split Function

var dateComponents = update_time.split(' ')[1].split('-');    //["2017", "06", "29"]
var formatedDate = `${dateComponents[1]}/${dateComponents[2]}/${dateComponents[0]}`;
console.log(formatedDate);

Or optionally you can use the momentJs library.

Vishnu Mishra
  • 3,683
  • 2
  • 25
  • 36
  • But he has a date string, not the current date. Although moment is a good library, neither moment nor the js Date object could recognize the exact format the OP's date was in. – Khauri Jul 01 '17 at 19:28
  • man, super simple, and completely understand now. Thank you! – AndroidDev21921 Jul 01 '17 at 19:55
  • 1
    Please don't recommend parsing strings with the Date constructor. This string has an associated time and timezone, reducing it to just the date part and parsing it with the built-in parser means it will be treated as UTC (or perhaps local or invalid in some browsers). So it will appear to be a different date for hosts with a timezone offset west of Greenwich. – RobG Jul 01 '17 at 21:14
  • @RobG You are correct. Updated to use the string only. Thanks. – Vishnu Mishra Jul 02 '17 at 05:14