0

Is there a one-liner to get this value:

1536634800

Out of

Timestamp(seconds=1536634800, nanoseconds=0)

?

Rosenberg
  • 2,424
  • 5
  • 33
  • 56
  • 1
    Possible duplicate of [Get Substring between two characters using javascript](https://stackoverflow.com/questions/14867835/get-substring-between-two-characters-using-javascript), where the two characters are `=` and `,`. – Heretic Monkey Aug 23 '18 at 22:54

4 Answers4

3

Use this regexp pattern:

console.log('Timestamp(seconds=1536634800, nanoseconds=0)'.match( /[0-9]{10}/g ));
shohrukh
  • 2,989
  • 3
  • 23
  • 38
  • yep more convenient than my answer :D – Hussein Aug 23 '18 at 22:56
  • Nice! Now I need to figure out how to convert it to a date format `mm/dd/yyyy` – Rosenberg Aug 23 '18 at 23:53
  • Just convert the result to number and pass to `Date` constructor: `new Date(Number(result))`. This will return a js date object which can be formatted as you wish. If you want more tricks with date, try to use some third party lib, for example 'moment.js' – shohrukh Aug 23 '18 at 23:57
  • @sherlock.92 Please elaborate your answer explaining how it works, not just post the code. Thanks for contributing! – Patricio Vargas Aug 24 '18 at 04:20
2
let str = "Timestamp(seconds=1536634800, nanoseconds=0)".split(',')[0].split("Timestamp(seconds=").reverse()[0];
console.log(str);
Hussein
  • 1,143
  • 1
  • 9
  • 16
0

To get the time inside of the string, you can do the following. Basically what is doing is using regex to match {10} numbers that are together.

TS

       let time = 'Timestamp(seconds=1536634800, nanoseconds=0)'.match( /[0-9]{10}/g );
         //Convert it into an actual date. Remeber to add a +1 to months since they start on zero 0.
        let parsedTime = new Date(parseInt(this.time[0]));

        //Store the formated date
        let fomarmatedDate = this.formatDate(this.parseTime);

        formatDate(time: Date) : String { 

        //In the mm we check if it's less than 9 because if it is your date will look like m/dd/yy
        // so we do some ternary to check the number and get the mm             
         let mm = time.getMonth()+1<9 ? `0${time.getMonth()+1}` : time.getMonth()+1;
         let dd = time.getDate();
         let yyyy = time.getFullYear();
         let date = `${mm}/${dd}/${yyyy}`;
         return date
        }

The result will be : 01/18/1970

You can make the code way shorter. I just did it this way so you can see how it works and what I'm doing.

To learn more about the .match take a look to this page https://www.w3schools.com/jsref/jsref_match.asp

You can use this tool to build your regex https://regexr.com/

Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
0
function extractHrefValue(inputString: string): string | null {
  const hrefRegex = /href\s*=\s*["']([^"']*)["']/i;
const match = inputString.match(hrefRegex);

if (match && match[1]) {
  return  match[1];
} else {
  return null;
}
}