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;