Display Date/Time in User's Locale Format and Time Offset

Display date/time in user's locale format and time offset

Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.

Then the various toLocale…String methods will provide localized output.

Example:

// This would come from the server.// Also, this whole block could probably be made into an mktime function.// All very bare here for quick grasping.d = new Date();d.setUTCFullYear(2004);d.setUTCMonth(1);d.setUTCDate(29);d.setUTCHours(2);d.setUTCMinutes(45);d.setUTCSeconds(26);
console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004console.log(d.toLocaleDateString()); // -> 02/28/2004console.log(d.toLocaleTimeString()); // -> 23:45:26

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Here's a simple helper function that will format JS dates for you.

function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};

return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}

var dt = new Date();
console.log(toIsoString(dt));

Formatting Dates and DateTimes for User's timezone including Timezone Offset in C# (.net)

Try using DateTimeOffset:

DateTimeOffset utcDto = new DateTimeOffset(utcDt, TimeSpan.Zero);
DateTimeOffset localDateTime = TimeZoneInfo.ConvertTime(utcDto, localTimeZone);
string dateString = localDateTime.ToString("dd MMM yy - HH:mm:ss (zzz)");

Create a Date with a set timezone without using a string representation

using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.

You cannot set it using UTC in the constructor though, unless you specify a date-string.

Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.

How to get exact time when converting date into string

Try this

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;

How ever format you want you may adjust

Getting the client's time zone (and offset) in JavaScript

Using getTimezoneOffset()

You can get the time zone offset in minutes like this:

var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01


Related Topics



Leave a reply



Submit