【问题标题】:Typescript - Extract a value from a stringTypescript - 从字符串中提取值
【发布时间】:2019-01-30 09:23:18
【问题描述】:

是否有单线可以得到这个值:

1536634800

没有

Timestamp(seconds=1536634800, nanoseconds=0)

?

【问题讨论】:

标签: angular typescript


【解决方案1】:

使用这个正则表达式模式:

console.log('Timestamp(seconds=1536634800, nanoseconds=0)'.match( /[0-9]{10}/g ));

【讨论】:

  • 是的,比我的回答更方便:D
  • 不错!现在我需要弄清楚如何将其转换为日期格式mm/dd/yyyy
  • 只需将结果转换为数字并传递给Date构造函数:new Date(Number(result))。这将返回一个 js 日期对象,可以根据需要进行格式化。如果您想要更多有关日期的技巧,请尝试使用一些第三方库,例如'moment.js'
  • @sherlock.92 请详细说明您的答案,解释它是如何工作的,而不仅仅是发布代码。感谢您的贡献!
【解决方案2】:
let str = "Timestamp(seconds=1536634800, nanoseconds=0)".split(',')[0].split("Timestamp(seconds=").reverse()[0];
console.log(str);

【讨论】:

    【解决方案3】:

    要获取字符串中的时间,您可以执行以下操作。基本上正在做的是使用正则表达式来匹配在一起的 {10} 数字。

    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
            }
    

    结果将是01/18/1970

    您可以使代码更短。我就是这样做的,这样你就可以看到它是如何工作的以及我在做什么。

    要了解有关 .match 的更多信息,请查看此页面https://www.w3schools.com/jsref/jsref_match.asp

    您可以使用此工具构建您的正则表达式https://regexr.com/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多