2017-01-28 23 views
0

在C#.NET,我可以很容易地改變這樣的日期格式:TypeScript日期格式選項類似於.NET中的那些選項?

DateTime date = new DateTime(); 
string date1 = date.ToString("dd MMM yy"); 
string date2 = date.ToString("yyyy/MM"); 
string date3 = date.ToString("MMMM d, yyyy"); 

等等...

我怎樣才能實現打字稿類似的東西?

回答

0

經過一番搜索後,我在marlun78寫的GitHub上發現了這個JavaScript file

因爲我想幫助其他人使用TypeScript,我決定在這裏發佈我的解決方案。所以我所做的是在TypeScript中重寫代碼。那就是:

export interface IFormatDateSettings { 
days?: string[]; 
daysAbbr?: string[]; 
designators?: string[]; 
defaultFormat?: string; 
months?: string[]; 
monthsAbbr?: string[]; 
os?: string[]; 
} 

/** 
* Date Format 
* Copyright (c) 2011, marlun78 
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83 
* 
* Format options inspired by the .NET framework's format. 
* http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx 
* 
* Non-formatting characters within the format string must be 
* quoted (single (') or double (") quotes)! The same is true 
* for two format specifiers that should apear together. Eg. 
* if you want the date to be output with the date ordinal 
* (9th), the format string must be "d''x" (or 'd""x'). 
* 
* Arguments: 
*  format {String} The format pattern to display the date in. See Format Patterns section below for options. 
*  settings {Object} Formatting settings. 
* 
* Settings: 
*  asUtc  {Boolean} If the formatted date is to be returned as a UTC date. 
*  days  {Array} The days of the week. Starting with Sunday. 
*  daysAbbr {Array} The days of the week, abbreviated. Starting with Sunday. 
*  designator {Array} Time designator. Starting with AM. 
*  format  {String} The format pattern to format the date in. 
*  months  {Array} The name of the months. Starting with January. 
*  monthsAbbr {Array} The name of the months, abbreviated. Starting with January. 
* 
* Format Patterns: 
*  d  1-31    The day of the month 
*  dd  01-31    The day of the month 
*  ddd  Mon-Sun    The abbreviated name of the day of the week 
*  dddd Monday-Sunday  The full name of the day of the week 
*  f  6     The tenths of a second in a date and time value. The remaining digits are truncated. 
*  ff  61     The hundredths of a second in a date and time value. The remaining digits are truncated. 
*  fff  617     The milliseconds in a date and time value. The remaining digits are truncated. 
*  ffff 6170    The milliseconds in a date and time value, with a trailing zero. The remaining digits are truncated. 
*  fffff 61700    The milliseconds in a date and time value, with two trailing zeros. The remaining digits are truncated. 
*  ffffff 617000    The milliseconds in a date and time value, with three trailing zeros. The remaining digits are truncated. 
*  F  6     The tenths of a second in a date and time value. Trailing zeros or zero values are not displayed. 
*  FF  61     The hundredths of a second in a date and time value. Trailing zeros or zero values are not displayed. 
*  FFF  617     The milliseconds in a date and time value. Trailing zeros or zero values are not displayed. 
*  FFFF 617     The milliseconds in a date and time value. Trailing zeros or zero values are not displayed. 
*  FFFFF 617     The milliseconds in a date and time value. Trailing zeros or zero values are not displayed. 
*  FFFFFF 617     The milliseconds in a date and time value. Trailing zeros or zero values are not displayed. 
*  h  1-12    The hour, using a 12-hour clock 
*  hh  01-12    The hour, using a 12-hour clock 
*  H  0-23    The hour, using a 24-hour clock 
*  HH  00-23    The hour, using a 24-hour clock 
*  m  0-59    The minute 
*  mm  00-59    The minute 
*  M  1-12    The month 
*  MM  01-12    The month 
*  MMM  Jan-Dec    The abbreviated name of the month 
*  MMMM January-December The full name of the month 
*  s  0-59    The second 
*  ss  00-59    The second 
*  tt  AM/PM    The AM/PM designator 
*  x  st, nd, rd, th  The ordinal suffix of a number (NOTE! This does not exist in .NET!) 
*  y  0-99    The year 
*  yy  00-99    The year 
*  yyy  001-9999   The year, with a minimum of three digits 
*  yyyy 0001-9999   The year as a four-digit number 
*  z  +1     Hours offset from UTC, with no leading zeros. 
*  zz  +01     Hours offset from UTC, with a leading zero for a single-digit value. 
*  zzz  +01:00    Hours and minutes offset from UTC. 
* 
* Example: 
*  The formatting method can be called in the following three ways: 
*  formatDate(format, settings) {String} The format string passed is used, any settings are stored. 
*           If the settings object contain a format property, it will override the format string. 
*  formatDate(settings)   {String} Settings are stored and the stored format is used. 
*  formatDate()     {String} Default settings are used. 
*/ 
export class FormatDateService { 

static settings: IFormatDateSettings = { 
    days: 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' '), 
    daysAbbr: 'Sun Mon Tue Wed Thu Fri Sat'.split(' '), 
    designators: 'AM PM'.split(' '), 
    defaultFormat: 'MMMM d""x "at" h:mm tt', 
    months: 'January February March April May June July August September October November December'.split(' '), 
    monthsAbbr: 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '), 
    os: 'th st nd rd th'.split(' ') 
}; 

asUtc: boolean = false; 

handlers = { 
    d: (date: Date, settings: IFormatDateSettings) => { return date[this.getMethod('Date')](); }, 
    dd: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('Date')]()); }, 
    ddd: (date: Date, settings: IFormatDateSettings) => { return this.getDayName(date, true, settings); }, 
    dddd: (date: Date, settings: IFormatDateSettings) => { return this.getDayName(date, undefined, settings); }, 
    f: (date: Date, settings: IFormatDateSettings) => { 
     return this.pad(this.pad(date[this.getMethod('Milliseconds')](), 3), 6, true).substr(0, 1); 
    }, 
    ff: (date: Date, settings: IFormatDateSettings) => { 
     return this.pad(this.pad(date[this.getMethod('Milliseconds')](), 3), 6, true).substr(0, 2); 
    }, 
    fff: (date: Date, settings: IFormatDateSettings) => { 
     return this.pad(this.pad(date[this.getMethod('Milliseconds')](), 3), 6, true).substr(0, 3); 
    }, 
    ffff: (date: Date, settings: IFormatDateSettings) => { 
     return this.pad(this.pad(date[this.getMethod('Milliseconds')](), 3), 6, true).substr(0, 4); 
    }, 
    fffff: (date: Date, settings: IFormatDateSettings) => { 
     return this.pad(this.pad(date[this.getMethod('Milliseconds')](), 3), 6, true).substr(0, 5); 
    }, 
    ffffff: (date: Date, settings: IFormatDateSettings) => { 
     return this.pad(this.pad(date[this.getMethod('Milliseconds')](), 3), 6, true).substr(0, 6); 
    }, 
    F: (date: Date, settings: IFormatDateSettings) => { 
     let r = this.pad(date[this.getMethod('Milliseconds')](), 3).substr(0, 1); return r === '0' ? '' : r; 
    }, 
    FF: (date: Date, settings: IFormatDateSettings) => { 
     let r = this.pad(date[this.getMethod('Milliseconds')](), 3).substr(0, 2); return r === '00' ? '' : r; 
    }, 
    FFF: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('Milliseconds')](), 3).substr(0, 3); }, 
    FFFF: (date: Date, settings: IFormatDateSettings) => { return this.handlers.FFF(date, settings); }, 
    FFFFF: (date: Date, settings: IFormatDateSettings) => { return this.handlers.FFF(date, settings); }, 
    FFFFFF: (date: Date, settings: IFormatDateSettings) => { return this.handlers.FFF(date, settings); }, 
    h: (date: Date, settings: IFormatDateSettings) => { let h = date[this.getMethod('Hours')](); return h > 12 ? h - 12 : h; }, 
    hh: (date: Date, settings: IFormatDateSettings) => { let h = date[this.getMethod('Hours')](); return this.pad(h > 12 ? h - 12 : h); }, 
    m: (date: Date, settings: IFormatDateSettings) => { return date[this.getMethod('Minutes')](); }, 
    mm: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('Minutes')]()); }, 
    H: (date: Date, settings: IFormatDateSettings) => { return date[this.getMethod('Hours')](); }, 
    HH: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('Hours')]()); }, 
    M: (date: Date, settings: IFormatDateSettings) => { return date[this.getMethod('Month')]() + 1; }, 
    MM: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('Month')]() + 1); }, 
    MMM: (date: Date, settings: IFormatDateSettings) => { return this.getMonthName(date, true, settings); }, 
    MMMM: (date: Date, settings: IFormatDateSettings) => { return this.getMonthName(date, undefined, settings); }, 
    s: (date: Date, settings: IFormatDateSettings) => { return date[this.getMethod('Seconds')](); }, 
    ss: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('Seconds')]()); }, 
    tt: (date: Date, settings: IFormatDateSettings) => { return this.getDesignator(date, settings); }, 
    x: (date: Date, settings: IFormatDateSettings) => { return this.getOrdinal(date, settings); }, 
    y: (date: Date, settings: IFormatDateSettings) => { 
     let y = date[this.getMethod('FullYear')](), s = y.toString(); return y < 10 ? y : s.substr(s.length - 2); 
    }, 
    yy: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('FullYear')](), 2); }, 
    yyy: (date: Date, settings: IFormatDateSettings) => { 
     let y = date[this.getMethod('FullYear')](), s = y.toString(); return y < 1000 ? this.pad(y, 3) : s.substr(s.length - 4); 
    }, 
    yyyy: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('FullYear')](), 4); }, 
    yyyyy: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('FullYear')](), 5); }, 
    yyyyyy: (date: Date, settings: IFormatDateSettings) => { return this.pad(date[this.getMethod('FullYear')](), 6); }, 
    z: (date: Date, settings: IFormatDateSettings) => { let t = date.getTimezoneOffset(); return (t > 0 ? '-' : '+') + Math.abs(t/60); }, 
    zz: (date: Date, settings: IFormatDateSettings) => { 
     let t = date.getTimezoneOffset(); return (t > 0 ? '-' : '+') + this.pad(Math.abs(t/60)); 
    }, 
    zzz: (date: Date, settings: IFormatDateSettings) => { 
     let t = date.getTimezoneOffset(); return (t > 0 ? '-' : '+') + 
      this.pad(Math.abs(t/60)) + ':' + this.pad((Math.abs(t/60) % 1) * 60); 
    } 
}; 

findPatterns: RegExp = /([dfFhmHMstxyz]+)(?=([^"']*["'][^"']*["'])*[^"']*$)/g; 

getMethod(method: string): string { 
    return 'get' + (this.asUtc ? 'UTC' : '') + method; 
}; 

public formatDate(date: Date, format: string = undefined, settings: IFormatDateSettings = undefined): string { 
    let usedSettings: IFormatDateSettings = FormatDateService.settings; 

    if (settings) { 
     usedSettings = Object.assign({}, FormatDateService.settings, settings); 
    } 

    if (!format) { 
     format = usedSettings.defaultFormat; 
    } 

    return format.replace(this.findPatterns, (match, group1) => { 
     let fn = this.handlers[group1]; 
     return typeof fn === 'function' ? fn(date, usedSettings) : match; 
    }).replace(/["']/g, ''); 
}; 


getDayName(date: Date, asAbbr: boolean, settings: IFormatDateSettings): string { 
    let n: number = date.getDay(); 
    return asAbbr ? settings.daysAbbr[n] : settings.days[n]; 
}; 

getMonthName(date: Date, asAbbr: boolean, settings: IFormatDateSettings): string { 
    let n: number = date.getMonth(); 
    return asAbbr ? settings.monthsAbbr[n] : settings.months[n]; 
}; 


getOrdinal(date: Date, settings: IFormatDateSettings): string { 
    let d: number = date.getDate(); 
    return (d > 3 && d < 21) ? settings.os[0] : settings.os[Math.min(d % 10, 4)]; 
} 

getDesignator(date: Date, settings: IFormatDateSettings): string { 
    return date.getHours() >= 12 ? settings.designators[1] : settings.designators[0]; 
}; 

pad(obj: any, len: any = undefined, fromRight: any = undefined): string { 
    let p = '000000'; 
    return fromRight ? 
     (obj + p).slice(0, len ? Math.min(len, p.length) : 2) : 
     (p + obj).slice(-(len ? Math.min(len, p.length) : 2)); 
} 
} 

您可以使用它像這樣:

let date:Date = new Date(); 
let formatdateService = new FormatDateService(); 
let formatedDate1:string = formatdateService.formatDate(date, 'dd MM yy'); 
let formatedDate2:string = formatdateService.formatDate(date, 'yyyy/MM'); 
let formatedDate3:string = formatdateService.formatDate(date, 'MMMM d, yyyy');