您的位置:首页 > 编程语言 > Delphi

Delphi获得与设置系统时间格式《转》

2017-11-16 14:42 381 查看
unit Unit1;

interface

uses

  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,

  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type

  TForm1 = class(TForm)

    btn1: TButton;

    btn2: TButton;

    Label1: TLabel;

    Label2: TLabel;

    Label3: TLabel;

    procedure btn1Click(Sender: TObject);

    procedure btn2Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

var

  Form1: TForm1;

  GPrevShortDate,GPrevLongDate,GPrevTimeFormat:string;
implementation

{$R *.dfm}

procedure GetDateTimeFormat();

const i = 100;

var

  buf:pchar;

begin

  getmem(buf,100);

  //i:=100; //i必须在调用前赋值为buf缓冲区的长度。如果设为0或负值,将取不到设置的值

  GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SSHORTDATE,buf,i); //取当前用户设置,短日期格式。

  GPrevShortDate:=string(buf);

  GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SLONGDATE,buf,i); //取长日期格式

  GPrevLongDate:=string(buf);

  GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_STIMEFORMAT,buf,i); //取时间格式

  GPrevTimeFormat:=string(buf);

  FreeMem(buf);

end;

procedure SetDateTimeFormat();

var

  p:DWORD;

begin

  SetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SSHORTDATE,pchar('yyyy/MM/dd')); //设置短日期格式

  SetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SLONGDATE,pchar('yyyy''年''M''月''d''日''')); //设置长日期格式为 yyyy'年'M'月'd'日',“年月日”字符必须用单引号括起来。Delphi字符串里必须用两个单引号。

  SetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_STIMEFORMAT,pchar('HH:mm:ss')); //设置时间格式,24小时制

  SendMessageTimeOut(HWND_BROADCAST,WM_SETTINGCHANGE,0,0,SMTO_ABORTIFHUNG,10,p);//设置完成后必须调用,通知其他程序格式已经更改,否则即使是程序自身也不能使用新设置的格式

end;

procedure TForm1.btn1Click(Sender: TObject);

begin

  SetDateTimeFormat;

  ShowMessage('修改成功!');

end;

procedure TForm1.btn2Click(Sender: TObject);

begin

  GetDateTimeFormat();

  label1.Caption := GPrevShortDate;

  Label2.Caption := GPrevLongDate;

  Label3.Caption := GPrevTimeFormat;

  ShowMessage('已得到原格式!');

end;

end.

在程序初始化时调用GetDateTimeFormat,将取出的设置保存起来,然后用SetDateTimeFormat设置需要的格式。在程序退出时再次调用SetDateTimeFormat将保存的值写回去。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: