Languages
[Edit]
PT

C# / .NET - obter carimbo de data / hora atual.

3 points
Created by:
Alyona
1114

Neste artigo, veremos como obter o registro de data e hora atual em C# / .NET. 

Existem duas maneiras disponíveis de se fazer isso: use métodos predefinidos ou formatação personalizada.

Solução rápida:

DateTimeOffset now = (DateTimeOffset)DateTime.UtcNow;  // using System;

Console.WriteLine(now.ToUnixTimeSeconds());            // .NET 4.6

Nota: leia este artigo para ver exemplos da ISO 8601.

 

V√° para as se√ß√Ķes abaixo para ver mais exemplos:

1. Exemplo de tempo Unix personalizado em segundos

Se queremos ter um código fonte que funcione com estruturas .net mais antigas, devemos usar esta solução:

using System;

public static class TimeUtils
{
	public static int ToUnixTimeSeconds(DateTime date)
	{
		DateTime point = new DateTime(1970, 1, 1);
		TimeSpan time = date.Subtract(point);

		return (int)time.TotalSeconds;
	}

	public static int ToUnixTimeSeconds()
	{
		return ToUnixTimeSeconds(DateTime.UtcNow);
	}
}

// Usage example:

public class Program
{
	public static void Main()
	{
		Console.WriteLine(TimeUtils.ToUnixTimeSeconds());
	}
}

Resultado:

1565641706

2. Exemplo de carimbo de data e hora do .NET 4.6 API Unix

O .net 4.6 introduziu um método especial que retorna o carimbo de data / hora do Unix.

using System;

public class Program
{
	public static void Main()
	{
		DateTimeOffset now = (DateTimeOffset)DateTime.UtcNow;

		Console.WriteLine(now.ToUnixTimeSeconds());
	}
}

Resultado:

1565642183

3. Exemplo predefinido de métodos da classe DateTime

Os métodos predefinidos disponíveis no .net retornam os formatos de hora mais usados.

Nota: √© muito importante consultar o CultureInfo atualmente usado¬†para saber que tipo de formata√ß√£o √© usada por padr√£o. √Č poss√≠vel chamar o m√©todo string com a cultura desejada.

using System;
using System.Globalization;

public class Program
{
	public static void Main()
	{
		DateTime now = DateTime.Now;

		CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

		Console.WriteLine(now.ToBinary());          // -8586359643687607670
		Console.WriteLine(now.ToFileTime());        // 132101161167168138
		Console.WriteLine(now.ToFileTimeUtc());     // 132101161167168138
		Console.WriteLine(now.ToLocalTime());       // 08/12/2019 21:41:56
		Console.WriteLine(now.ToLongDateString());  // Monday, 12 August 2019
		Console.WriteLine(now.ToLongTimeString());  // 21:41:56
		Console.WriteLine(now.ToOADate());          // 43689.9041286574
		Console.WriteLine(now.ToShortDateString()); // 08/12/2019
		Console.WriteLine(now.ToShortTimeString()); // 21:41
		Console.WriteLine(now.ToString());          // 08/12/2019 21:41:56
	}
}

Resultado:

-8586359643687607670
132101161167168138
132101161167168138
08/12/2019 21:41:56
Monday, 12 August 2019
21:41:56
43689.9041286574
08/12/2019
21:41
08/12/2019 21:41:56
Nota: A propriedade¬†CultureInfo.CurrentCulture¬†causa formata√ß√£o de seq√ľ√™ncia espec√≠fica para n√ļmeros, moedas, hora, etc.

4. ToString método com exemplo de formato personalizado

Nesta seção, apresentamos como usar o formato personalizado para imprimir data e hora formatadas - o formato pode ser modificado, se necessário.

using System;
using System.Globalization;

public class Program
{
	public static void Main()
	{
		DateTime dt = new DateTime(2018, 2, 15, 8, 21, 34, 547);
		CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

		Console.WriteLine(dt.ToString("dddd, dd MMMM yyyy HH:mm"));    // e.g. 1
		Console.WriteLine(dt.ToString("dddd, dd MMMM yyyy HH:mm tt")); // e.g. 2
	}
}

Resultado:

Thursday, 15 February 2018 08:21      // e.g. 1
Thursday, 15 February 2018 08:21 AM   // e.g. 2

Para diferentes formatos ToString, os resultados são os seguintes:

/*

FORMAT                            RESULT                                    EXAMPLE NUMBER

dddd, dd MMMM yyyy HH:mm          Thursday, 15 February 2018 08:21          1
dddd, dd MMMM yyyy HH:mm tt       Thursday, 15 February 2018 08:21 AM       2
dddd, dd MMMM yyyy HH:mm:ss       Thursday, 15 February 2018 08:21:34       3
dddd, dd MMMM yyyy HH:mm:ss tt    Thursday, 15 February 2018 08:21:34 AM    4
dddd, dd MMMM yyyy H:mm           Thursday, 15 February 2018 8:21           5
dddd, dd MMMM yyyy H:mm tt        Thursday, 15 February 2018 8:21 AM        6
dddd, dd MMMM yyyy H:mm:ss        Thursday, 15 February 2018 8:21:34        7
dddd, dd MMMM yyyy H:mm:ss tt     Thursday, 15 February 2018 8:21:34 AM     8
dddd, dd MMMM yyyy hh:mm          Thursday, 15 February 2018 08:21          9
dddd, dd MMMM yyyy hh:mm tt       Thursday, 15 February 2018 08:21 AM       10
dddd, dd MMMM yyyy hh:mm:ss       Thursday, 15 February 2018 08:21:34       11
dddd, dd MMMM yyyy hh:mm:ss tt    Thursday, 15 February 2018 08:21:34 AM    12
dddd, dd MMMM yyyy h:mm           Thursday, 15 February 2018 8:21           13
dddd, dd MMMM yyyy h:mm tt        Thursday, 15 February 2018 8:21 AM        14
dddd, dd MMMM yyyy h:mm:ss        Thursday, 15 February 2018 8:21:34        15
dddd, dd MMMM yyyy h:mm:ss tt     Thursday, 15 February 2018 8:21:34 AM     16
MM/dd/yyyy HH:mm                  02/15/2018 08:21                          17
MM/dd/yyyy HH:mm tt               02/15/2018 08:21 AM                       18
MM/dd/yyyy HH:mm:ss               02/15/2018 08:21:34                       19
MM/dd/yyyy HH:mm:ss tt            02/15/2018 08:21:34 AM                    20
MM/dd/yyyy H:mm                   02/15/2018 8:21                           21
MM/dd/yyyy H:mm tt                02/15/2018 8:21 AM                        22
MM/dd/yyyy H:mm:ss                02/15/2018 8:21:34                        23
MM/dd/yyyy H:mm:ss tt             02/15/2018 8:21:34 AM                     24
MM/dd/yyyy hh:mm                  02/15/2018 08:21                          25
MM/dd/yyyy hh:mm tt               02/15/2018 08:21 AM                       26
MM/dd/yyyy hh:mm:ss               02/15/2018 08:21:34                       27
MM/dd/yyyy hh:mm:ss tt            02/15/2018 08:21:34 AM                    28
MM/dd/yyyy h:mm                   02/15/2018 8:21                           29
MM/dd/yyyy h:mm tt                02/15/2018 8:21 AM                        30
MM/dd/yyyy h:mm:ss                02/15/2018 8:21:34                        31
dddd, dd MMMM yy                  Thursday, 15 February 18                  32
dddd, dd MMMM yyyy                Thursday, 15 February 2018                33
MM/dd/yy                          02/15/18                                  34
MM/dd/yyyy                        02/15/2018                                35
MMMM dd                           February 15                               36
yy-MM-dd                          18-02-15                                  37
yyyy-MM-dd                        2018-02-15                                38
yy.MM.dd                          18.02.15                                  39
yyyy.MM.dd                        2018.02.15                                40
dd.MM.yy                          15.02.18                                  41
dd.MM.yyyy                        15.02.2018                                42
yyyy MMMM                         2018 February                             43
ddd, MMM d, yyyy                  Thu, Feb 15, 2018                         44
dddd, MMMM d, yyyy                Thursday, February 15, 2018               45
yyyy-MM-ddTHH:mm:ss               2018-02-15T08:21:34                       46
yyyy-MM-ddTHH:mm:ss.fffffffK      2018-02-15T08:21:34.5470000               47
yyyyMMddHHmmss                    20180215082134                            48
yyyyMMddHHmmssfffffff             201802150821345470000                     49
ddd, dd MMM yyy HH:mm:ss 'GMT'    Thu, 15 Feb 2018 08:21:34 GMT             50
HH:mm                             08:21                                     51
HH:mm tt                          08:21 AM                                  52
HH:mm:ss                          08:21:34                                  53
HH:mm:ss tt                       08:21:34 AM                               54
H:mm                               8:21                                     55
H:mm tt                            8:21 AM                                  56
H:mm:ss                            8:21:34                                  57
H:mm:ss tt                         8:21:34 AM                               58
hh:mm                             08:21                                     59
hh:mm tt                          08:21 AM                                  60
hh:mm:ss                          08:21:34                                  61
hh:mm:ss tt                       08:21:34 AM                               62
h:mm                               8:21                                     63
h:mm tt                            8:21 AM                                  64
h:mm:ss                            8:21:34                                  65


Where:
       H -  0-23 hours
      HH - 00-23 hours         (zeros are printed to keep two places)
       h -  0-12 hours
      hh - 00-12 hours         (zeros are printed to keep two places)
      mm - 00-59 minutes       (zeros are printed to keep two places)
      ss - 00-59 seconds       (zeros are printed to keep two places)
      tt - AM or PM
 fffffff - second fraction
fffffffK - second fraction

       d - day of month number
      dd - day of month number (zeros are printed to keep two places)
     ddd - short day name
    dddd - long day name
      MM - month number        (zeros are printed to keep two places)
     MMM - short month name
    MMMM - long month name
      yy - 00-99 year          (zeros are printed to keep two places)
     yyy - 00-999 year         (zeros are printed to keep two places)
    yyyy - 00-9999 year        (zeros are printed to keep two places)

  Charactes that are not interpreted: T - : . ,

  'text' - single apostrophe does not interpret text inside e.g. 'GMT' as GMT

*/

Referências:

  1. DateTimeOffset.ToUnixTimeSeconds Method - Microsoft Docs
  2. DateTime Class - Microsoft Docs
  3. CultureInfo.CurrentCulture property - Microsoft Docs
  4. Custom date and time format strings - Microsoft Docs
  5. Standard Date and Time Format Strings - Microsoft Docs
Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.