Skip to content

Instantly share code, notes, and snippets.

@vurdalakov
Last active April 13, 2021 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vurdalakov/3388bf8ffc2fdb635db28f2512766c11 to your computer and use it in GitHub Desktop.
Save vurdalakov/3388bf8ffc2fdb635db28f2512766c11 to your computer and use it in GitHub Desktop.
Format the current local system time using the preferences set in the regional and language options portion of Control Panel
namespace Vurdalakov
{
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
public static class DateTimeApi
{
public static String GetCurrentTimeString(Boolean shortTime)
{
var stringBuffer = new StringBuilder(LOCALE_NAME_MAX_LENGTH + 1);
var result = GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, shortTime ? TIME_NOSECONDS : 0, IntPtr.Zero, null, stringBuffer, stringBuffer.Capacity);
if (result != 0)
{
return stringBuffer.ToString();
}
Trace.WriteLine($"GetTimeFormatEx() failed with error {Marshal.GetLastWin32Error()}");
return DateTime.Now.ToString(shortTime ? "t" : "T", System.Globalization.CultureInfo.InstalledUICulture);
}
private const String LOCALE_NAME_INVARIANT = "";
private const String LOCALE_NAME_USER_DEFAULT = null;
private const String LOCALE_NAME_SYSTEM_DEFAULT = "!x-sys-default-locale";
private const Int32 LOCALE_NAME_MAX_LENGTH = 85;
private const Int32 TIME_NOMINUTESORSECONDS = 1;
private const Int32 TIME_NOSECONDS = 2;
private const Int32 TIME_NOTIMEMARKER = 4;
private const Int32 TIME_FORCE24HOURFORMAT = 8;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern Int32 GetTimeFormatEx(String locale, UInt32 dwFlags, IntPtr sysTime, String lpFormat, StringBuilder lpDateStr, Int32 cchDate);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment