Delphi的日期时间格式

1、日期时间格式化为字符串

  edit2.text:=formatdatetime( 'yyyy年mm月dd日hh点nn分ss秒',now);

2、将程序初始化为指定的日期时间格式(在程序初始化时处理)

  System.SysUtils.FormatSettings.DateSeparator   := '-';
  System.SysUtils.FormatSettings.ShortDateFormat := 'yyyy-mm-dd';
  System.SysUtils.FormatSettings.LongDateFormat  := 'yyyy-mm-dd';
  System.SysUtils.FormatSettings.LongTimeFormat  := 'HH:mm:ss';

3、日期时间/字符串互相转换函数

//Desc: 本地化格式
function LocalDTSettings: TFormatSettings;
begin
  Result := TFormatSettings.Create('en-US');
  //default config  

  with Result do
  begin
    ShortDateFormat:='yyyy-MM-dd';
    DateSeparator  :='-';
    LongTimeFormat :='hh:mm:ss';
    TimeSeparator  :=':';
  end;
end;

//Desc: 转换为日期型
class function TDateTimeHelper.Str2Date(const nStr: string): TDate;
begin
  try
    Result := StrToDate(nStr, LocalDTSettings);
  except
    Result := Date();
  end;
end;

//Desc: 日期转字符串
class function TDateTimeHelper.Date2Str(const nDate: TDateTime;
  const nSeparator: Boolean): string;
begin
  if nSeparator then
       Result := FormatDateTime('YYYY-MM-DD', nDate)
  else Result := FormatDateTime('YYYYMMDD', nDate);
end;

//Desc: 转换为时间型
class function TDateTimeHelper.Str2Time(const nStr: string): TTime;
begin
  try
    Result := StrToTime(nStr, LocalDTSettings);
  except
    Result := Time();
  end;
end;

class function TDateTimeHelper.Time2Str(const nTime: TDateTime;
  const nSeparator,nMSec: Boolean): string;
begin
  if nSeparator then
  begin
    Result := 'HH:MM:SS';
    if nMSec then
      Result := Result + ':ZZZ';
    //Milliseconds
  end else
  begin
    Result := 'HHMMSS';
    if nMSec then
      Result := Result + 'ZZZ';
    //Milliseconds
  end;

  Result := FormatDateTime(Result, nTime);
end;

class function TDateTimeHelper.Str2DateTime(const nStr: string): TDateTime;
begin
  try
    Result := StrToDateTime(nStr, LocalDTSettings);
  except
    Result := Now();
  end;
end;

//Desc: 日期转字符串
class function TDateTimeHelper.DateTime2Str(const nDT: TDateTime): string;
begin
  Result := FormatDateTime('yyyy-mm-dd hh:mm:ss', nDT);
end;

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值