格式化日期和时间 [英] Formatting Dates and Times
问题描述
我真的那么傻吗? [不回答]
我想将日期和时间格式化为LOCALE格式,因此英国的计算机将显示30/07/2012
和1,234.56
,美国的07/30/2012
和1,234.56
,以及匈牙利的2012.07.30.
和1 234,56
.
日期很简单:
Am I really that stupid? [no don''t answer]
I want to format dates and times to LOCALE format, so a UK machine would show 30/07/2012
and 1,234.56
, an American 07/30/2012
and 1,234.56
, and a Hungarian 2012.07.30.
and 1 234,56
.
The date is simple:
var dateSting = new Date(2012,07,30,0,0,0).toLocaleDateString(); // or something
现在,是否有一种简单,快速且可靠的方式将数字格式化为本地样式?
**编辑**
我不好!我想格式化一个NUMBER,日期部分可以.
Now, is there an easy, quick and RELIABLE way to format a number to the local style?
** EDIT **
Me bad! I want to format a NUMBER, the date part is okay.
推荐答案
^ ]
您已经很近了.
toLocaleString[^]
you were close.
DateTime date=DateTime.Now;
//Sets the CurrentCulture property to U.S. English.
System.Globalization.CultureInfo c2 = new System.Globalization.CultureInfo("en-US");
Label1.Text = date.ToString("d",c2);
// Creates a CultureInfo for German in Germany.
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("de-DE");
Label2.Text = date.ToString("d",ci);
设置为
us = CultureInfo("en-US");
英国= CultureInfo("en-GB");
丹麦文= CultureInfo("da");
以及更多的CultureInfo http://msdn.microsoft.com /en-us/library/system.globalization.cultureinfo(v=vs.71).aspx [
set For
us = CultureInfo("en-US");
british = CultureInfo("en-GB");
danish = CultureInfo("da");
and for more CultureInfo http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.71).aspx[^]
我对自己的状态并不十分自信答案不会因滚动眼睛或敌意而被接受-尽管它确实似乎至少可以正常工作,但它肯定相当草率.
我想您总是可以(不停地)检查返回的日期字符串表示形式,以此作为猜测/确定用于转换数字的适当例程的一种方法.
运行时,输出为
I''m not terribly confident that my answer wont be met with rolling eyes or hostility - it certainly is fairly sloppy - though it does appear to at least work.
I guess you could always (shudder) examine the returned string representation of the date as a means of guessing/determining the appropriate routine to use to convert the number.
When run, the output is
3,141,592.653589793
3141592,653589793
<!DOCTYPE html>
<html>
<head>
<script>
function convNum()
{
var inNum = 1000000 * 3.141592653589793;
document.getElementById('ukUs').innerHTML = toUkUs(inNum);
document.getElementById('hung').innerHTML = toHung(inNum);
}
function toHung(num)
{
var str = String(num);
return str.replace('.', ',');
}
function toUkUs(num)
{
var str = thousandSeparator(num,',');
var n=str.indexOf(".");
var preDec = str.substring(0,n);
var postDec ='';
for (i=n; i<str.length; i++)
{
if (str.charAt(i) != ',')
postDec += str.charAt(i);
}
return preDec + postDec;
}
function thousandSeparator(n,sep) {
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'), sValue=n+'';
if (sep === undefined) {sep=',';}
while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, '
这篇关于格式化日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!