c#时间 转换成java_你如何在C#中转换纪元时间?

回答(10)

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

我认为你的意思是Unix time,它被定义为1970年1月1日午夜(UTC)以来的秒数 .

public static DateTime FromUnixTime(long unixTime)

{

return epoch.AddSeconds(unixTime);

}

private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

有了LukeH的全部功劳,我将一些扩展方法放在一起以方便使用:

public static DateTime FromUnixTime(this long unixTime)

{

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

return epoch.AddSeconds(unixTime);

}

public static long ToUnixTime(this DateTime date)

{

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

return Convert.ToInt64((date - epoch).TotalSeconds);

}

请注意以下来自CodesInChaos的评论,上面的 FromUnixTime 返回一个带有 Kind Utc 的 DateTime ,这很好,但上面的 ToUnixTime 更令人怀疑,因为它没有考虑给定的 date 是什么类型的 DateTime . 要允许 date 的 Kind 为 Utc 或 Local ,请使用ToUniversalTime:

public static long ToUnixTime(this DateTime date)

{

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);

}

ToUniversalTime 会将 Local (或 Unspecified ) DateTime 转换为 Utc .

如果你不想在从DateTime移动到epoch时创建epoch DateTime实例,你也可以这样做:

public static long ToUnixTime(this DateTime date)

{

return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;

}

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

latest version of .Net (v4.6)刚刚添加了对Unix时间转换的内置支持 . 这包括来自Unix时间和来自Unix或毫秒的时间 .

Unix时间以秒为单位 DateTimeOffset :

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);

DateTimeOffset 到Unix时间秒:

long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();

Unix时间(以毫秒为单位)到 DateTimeOffset :

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);

DateTimeOffset 到Unix时间,以毫秒为单位:

long unixTimeStampInMilliseconds= dateTimeOffset.ToUnixTimeMilliseconds();

注意:这些方法与 DateTimeOffset 进行转换 . 要获得 DateTime 表示,只需使用 DateTimeOffset.DateTime 属性:

DateTime dateTime = dateTimeOffset.UtcDateTime;

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

你实际上想要AddMilliseconds(毫秒),而不是秒 . 添加秒将使您超出范围异常 .

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

// convert datetime to unix epoch seconds

public static long ToUnixTime(DateTime date)

{

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);

}

应该使用ToUniversalTime()作为DateTime对象 .

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

如果您想获得更好的性能,可以使用此版本 .

public const long UnixEpochTicks = 621355968000000000;

public const long TicksPerMillisecond = 10000;

public const long TicksPerSecond = TicksPerMillisecond * 1000;

//[MethodImpl(MethodImplOptions.AggressiveInlining)]

public static DateTime FromUnixTimestamp(this long unixTime)

{

return new DateTime(UnixEpochTicks + unixTime * TicksPerSecond);

}

从net471下的快速基准测试(BenchmarkDotNet)我得到这个数字:

Method | Mean | Error | StdDev | Scaled |

-------------- |---------:|----------:|----------:|-------:|

LukeH | 5.897 ns | 0.0897 ns | 0.0795 ns | 1.00 |

MyCustom | 3.176 ns | 0.0573 ns | 0.0536 ns | 0.54 |

这与DateTime内部工作方式类似 .

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

我使用以下扩展方法进行纪元转换

public static int GetEpochSeconds(this DateTime date)

{

TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);

return (int)t.TotalSeconds;

}

public static DateTime FromEpochSeconds(this DateTime date, long EpochSeconds)

{

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

return epoch.AddSeconds(EpochSeconds);

}

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

如果您需要将包含 UNIX time 的timeval struct(秒,微秒)转换为 DateTime 而不会丢失精度,请按以下方式操作:

DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

private DateTime UnixTimeToDateTime(Timeval unixTime)

{

return _epochTime.AddTicks(

unixTime.Seconds * TimeSpan.TicksPerSecond +

unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);

}

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

///

/// DateTime as UTV for UnixEpoch

///

public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

///

/// Per JWT spec:

/// Gets the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the desired date/time.

///

/// The DateTime to convert to seconds.

/// if dateTimeUtc less than UnixEpoch, return 0

/// the number of seconds since Unix Epoch.

public static long GetIntDate(DateTime datetime)

{

DateTime dateTimeUtc = datetime;

if (datetime.Kind != DateTimeKind.Utc)

{

dateTimeUtc = datetime.ToUniversalTime();

}

if (dateTimeUtc.ToUniversalTime() <= UnixEpoch)

{

return 0;

}

return (long)(dateTimeUtc - UnixEpoch).TotalSeconds;

}

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

这是我的解决方案:

public long GetTime()

{

DateTime dtCurTime = DateTime.Now.ToUniversalTime();

DateTime dtEpochStartTime = Convert.ToDateTime("1/1/1970 0:00:00 AM");

TimeSpan ts = dtCurTime.Subtract(dtEpochStartTime);

double epochtime;

epochtime = ((((((ts.Days * 24) + ts.Hours) * 60) + ts.Minutes) * 60) + ts.Seconds);

return Convert.ToInt64(epochtime);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 私钥转换为 Java 私钥的过程如下: 1. 首先,将 C# 私钥导出为 XML 格式。 2. 使用 Java 的密钥库管理工具(如 Keytool)创建一个新的 Java 密钥库文件。 3. 从 XML 文件提取私钥和公钥,然后将它们转换为 Java 的 PrivateKey 和 PublicKey 对象。可以使用 Java 的 Bouncy Castle 库来完这一步骤。 4. 将 PrivateKey 和 PublicKey 对象存储到 Java 密钥库文件。 5. 将 Java 密钥库文件导出为 JKS 格式。 下面是 C# 密钥转换为 Java 密钥库的示例代码: ```csharp // 导出 C# 私钥为 XML 格式 CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "MyKeyContainer"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams); string privateKeyXml = rsa.ToXmlString(true); // 将 XML 格式的私钥转换为 Java 私钥对象 var doc = new XmlDocument(); doc.LoadXml(privateKeyXml); var rsaParams = new RSAParameters(); rsaParams.Modulus = Convert.FromBase64String(doc.GetElementsByTagName("Modulus")[0].InnerText); rsaParams.Exponent = Convert.FromBase64String(doc.GetElementsByTagName("Exponent")[0].InnerText); rsaParams.P = Convert.FromBase64String(doc.GetElementsByTagName("P")[0].InnerText); rsaParams.Q = Convert.FromBase64String(doc.GetElementsByTagName("Q")[0].InnerText); rsaParams.DP = Convert.FromBase64String(doc.GetElementsByTagName("DP")[0].InnerText); rsaParams.DQ = Convert.FromBase64String(doc.GetElementsByTagName("DQ")[0].InnerText); rsaParams.InverseQ = Convert.FromBase64String(doc.GetElementsByTagName("InverseQ")[0].InnerText); rsaParams.D = Convert.FromBase64String(doc.GetElementsByTagName("D")[0].InnerText); RSACryptoServiceProvider rsaJava = new RSACryptoServiceProvider(); rsaJava.ImportParameters(rsaParams); // 将 Java 私钥存储到密钥库 var keyStore = KeyStore.GetInstance(KeyStore.DefaultType); keyStore.Load(null, null); keyStore.SetKeyEntry("mykey", rsaJava, null, null); var outputStream = new FileOutputStream("mykeystore.jks"); keyStore.Store(outputStream, "mypassword".ToCharArray()); outputStream.Close(); ``` 使用 Bouncy Castle 库将 XML 格式的 C# 公钥转换为 Java 公钥对象的示例代码如下: ```java // 将 C# 公钥转换为 Java 公钥对象 var doc = new XmlDocument(); doc.LoadXml(publicKeyXml); var rsaParams = new RSAParameters(); rsaParams.Modulus = Convert.FromBase64String(doc.GetElementsByTagName("Modulus")[0].InnerText); rsaParams.Exponent = Convert.FromBase64String(doc.GetElementsByTagName("Exponent")[0].InnerText); RSACryptoServiceProvider rsaJava = new RSACryptoServiceProvider(); rsaJava.ImportParameters(rsaParams); var publicKey = rsaJava.ExportParameters(false); // 将 Java 公钥存储到密钥库 var keyStore = KeyStore.GetInstance(KeyStore.DefaultType); keyStore.Load(null, null); keyStore.SetCertificateEntry("mycert", new X509Certificate()); keyStore.SetKeyEntry("mykey", publicKey, null, null); var outputStream = new FileOutputStream("mykeystore.jks"); keyStore.Store(outputStream, "mypassword".ToCharArray()); outputStream.Close(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值