how to display tomorrow's full date in javascript - javascript

I have the following script:
document.write('<p><span id="date-time">', new Date().toLocaleString(), '<\/span>.<\/p>')
if (document.getElementById) onload = function () {
setInterval("document.getElementById ('date-time').firstChild.data = new Date().toLocaleString()", 50)
}
It displays:
Friday, January 09, 2015 12:20 PM.
How can I display tomorrow's date in the same format leaving the time off?

You can do it setting custom options for toLocaleString, see MDN documentation for toLocaleString
To solve your question:
var tomorrow = new Date(Date.now() + 1000 * 3600 * 24);
var result = tomorrow.toLocaleString('en-US', { weekday: 'long', month: 'long', year: 'numeric', day: 'numeric' });
document.write('<p><span id="date-time">', result, '<\/span>.<\/p>');
See this fiddle.

This will add +1 to result of getDate(), which is current day, then prints with given formatting.
var tomorrow = new Date(new Date().setDate(new Date().getDate()+1));
console.log(tomorrow.toLocaleString('en-US', { weekday: 'long', month: 'long', year: 'numeric', day: 'numeric' }));
Note that this will print the date in same format across all destinations and languages, unlike the toLocaleString() without parameters.
...
/edit
Possibly neater way to increment the day by one is
var date = new Date();
date.setDate(date.getDate() + 1);
// date.toLocaleString(...) remains the same as above

A date can be represented by the number of milliseconds since the epoch (1 January, 1970, 00:00:00 UTC in javascripts case)
One day is 86400000 milliseconds (24 * 60 * 60 *1000)
Create a Date object for today,then get the millisecond representation (getTime) and add one days worth of milliseconds
Create (using the constructor) or modify a Date object (using setTime method) from this millisecond representation and then use the toDateString method to return just the date portion as a string.
Or for a language sensitive representation use toLocaleDateString
Note: toLocaleDateString has limited browser support and so you may have to perform manual formatting yourself.
Where can I find documentation on formatting a date in JavaScript?
var todayObj = new Date()
tomorrowMs = todayObj.getTime() + 86400000,
tomorrowObj = new Date(tomorrowMs),
tomorrowDateStr = tomorrowObj.toDateString();
document.body.appendChild(document.createTextNode(tomorrowDateStr));

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var str = tomorrow.toLocaleString().substring(0,tomorrow.toLocaleString().indexOf(':')-3);
document.write('<p><span id="date-time">', str, '<\/span>.<\/p>')
if (document.getElementById) onload = function () {
setInterval("document.getElementById ('date-time').firstChild.data = str", 50)
}
As #Qwerty noted, you will not always get the exact same format in all computers.

Related

Converting to local time using UTC time zone format in Javascript

Been trying to wrap my head around this for a good time now, but I can't think of a good way to do it.
I have an array with a bunch of different UTC time zones (in just format -07, -01, +03, +10, etc). What I'm trying to achieve is a way to show the local time of those time zones, possibly including the day and month.
Here's an example of the resulting string: Local time: 14:09 23/08
You can use Date.prototype.getTimezoneOffset() to get your local timezone. Calculate the difference between your local timezone and the destination timezone, multiply it with 3600000 and add it to a Date object containing the current time.
const now = new Date();
const timezoneOffset = now.getTimezoneOffset() / 60;
const timezones = ['-07', '-01', '+03', '+10'];
timezones.forEach(timezone => {
const difference = +timezone + timezoneOffset;
const time = new Date(now.getTime() + difference * 3600000);
console.log(`Local time: ${time.toLocaleTimeString([], { timeStyle: 'short', hour12: false })} ${time.toLocaleDateString([], { month: '2-digit', day: '2-digit' })}`);
});

Json Stringify date produces a wrong date compared to javascript date

When i create a javascript date and then stringify it and send it to the server, i get two different dates. The stringified date is always one day behind.
So currently i increment my javascript date by 1 day so that i receive the same date on the server.
my current code:
var dt = $(.datepicker).datepicker('getDate');//Fri Aug 26 2016 00:00:00 GMT+0200 (South Africa Standard Time)
var result = Json.stringify(dt); //"2016-08-25T22:00:00.000Z"
Is this the correct approach or am i missing something?
This is due to the timezone component in the Date. The work around I did was:
var date = $(.datepicker).datepicker('getDate');
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()))
var result = Json.stringify(utcDate);
The removes the timezone component.
You don't seem to understand that both of your datetimes are actually the same and are correct. You haven't explained why you think that you need to manually alter the one sent to the server. Here is an example that demonstrates that they are in fact the same, just displayed in different formats in different timezones.
// Values from the local datetime string
var local = {
year: 2016,
month: 7,
day: 26,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Values from the UTC ISO 8601 datetime string
var utc = {
year: 2016,
month: 7,
day: 25,
hours: 22,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Create Date object as local
var date1 = new Date(
local.year,
local.month,
local.day,
local.hours,
local.minutes,
local.seconds,
local.milliseconds
);
// Create Date object as local from UTC
var date2 = new Date(Date.UTC(
utc.year,
utc.month,
utc.day,
utc.hours,
utc.minutes,
utc.seconds,
utc.milliseconds
));
var pre = document.getElementById('out');
// Display Date1 as local
pre.appendChild(document.createTextNode(date1.toString() + '\n'));
// Display Date2 as local
pre.appendChild(document.createTextNode(date2.toString() + '\n'));
// Display Date2 as UTC
pre.appendChild(document.createTextNode(date2.toUTCString() + '\n'));
// Test if Date1 and Date2 display the same datetime
pre.appendChild(document.createTextNode(
'Date1 === Date2: ' + (date1.getTime() === date2.getTime())
));
<pre id="out"></pre>
JSON converts Date objects to ISO 8601 (by specification), but let's see what happens if you use the solution that you chose.
// Values from the local datetime string
var local = {
year: 2016,
month: 7,
day: 26,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Create Date object as local
var date = new Date(
local.year,
local.month,
local.day,
local.hours,
local.minutes,
local.seconds,
local.milliseconds
);
// Your solution
var utcDate = new Date(Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes()));
var pre = document.getElementById('out');
// Display Date as local format
pre.appendChild(document.createTextNode(date.toString() + '\n'));
// Display utcDate as local format
pre.appendChild(document.createTextNode(utcDate.toString() + '\n'));
// Test if Date and utcDate display the same datetime
pre.appendChild(document.createTextNode(
'Date1 === Date2: ' + (date.getTime() === utcDate.getTime())
));
<pre id="out"></pre>
You end up with 2 dates that are no longer the same. Don't like ISO 8601 for transmission and storage of datetimes? Well the alternative would be to use the number of milliseconds UTC since the epoch (getTime). You can't make JSON do this conversion instead of ISO 8601, not even using a replacer function. So any conversion would be necessary before using JSON.stringify. So you really need to explain what it is you are trying to achieve and why you think what you have now is incorrect.
Use this
var result = Json.stringify(dt.toISOString());

How to display a Date object in a specific format using JavaScript?

I have a Date object and I'd like to display it in the below format:
var myDate = getDate();
// this format: "13 Jan 2012 11:00am";
How would that be possible?
Thanks,
Use the build-in toLocaleString()
const date = new Date();
const formattedDate = date.toLocaleString("en-GB", {
day: "numeric",
month: "short",
year: "numeric",
hour: "numeric",
minute: "2-digit"
});
console.log(formattedDate); // '18 Jan 2020, 18:20'
EDIT: For modern apps (without IE support) please see the answer by #zendka https://stackoverflow.com/a/59802446/483616
There is a great JavaScript library that handles this very well, and only 5.5kb minified.
http://momentjs.com/
It looks something like this:
moment().format('MMMM Do YYYY, h:mm:ss a'); // February 25th 2013, 9:54:04 am
moment().subtract('days', 6).calendar(); // "last Tuesday at 9:53 AM"
You can also pass in dates as a String with a format, or a Date object.
var date = new Date();
moment(date); // same as calling moment() with no args
// Passing in a string date
moment("12-25-1995", "MM-DD-YYYY");
Also has great support for languages other than English, like Russian, Japanese, Arabic, Spanish and others.
Check out the docs.
If you do not want to use any libraries:
<script type="text/javascript">
var myDate = new Date();
var month=new Array();
month[0]="Jan";
month[1]="Feb";
month[2]="Mar";
month[3]="Apr";
month[4]="May";
month[5]="Jun";
month[6]="Jul";
month[7]="Aug";
month[8]="Sep";
month[9]="Oct";
month[10]="Nov";
month[11]="Dec";
var hours = myDate.getHours();
var minutes = myDate.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ampm;
// e.g. "13 Nov 2016 11:00pm";
alert(myDate.getDate()+" "+month[myDate.getMonth()]+" "+myDate.getFullYear()+" "+strTime);
</script>
There are many date formatting packages available for javascript, I've had great success with Steven Levithan's dateformat.
dateFormat(getDate(), "dd mmm yyyy hh:MMtt");
Edit: It also adds a format method to Date.prototype, if you enjoy that style:
getDate().format("dd mmm yyyy hh:MMtt");
Another JavaScript built-in library that you could now use to format a date, is the Intl library.
// use formatToParts() to convert a date and put it into an array for the different parts of the date
var customDateArray = new Intl.DateTimeFormat('en-US', { day: 'numeric', month: 'short', year: 'numeric', hour: 'numeric', minute: 'numeric' }). formatToParts(new Date()),
dateParts = {}
// This converts the array to an object to make it easier to pick out what you want using template literals.
customDateArray.map(({type, value}) => {
dateParts[type] = value
})
console.log(`${dateParts.day} ${dateParts.month} ${dateParts.year} ${dateParts.hour}:${dateParts.minute}${dateParts.dayPeriod.toLowerCase()}`)
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
Have a look at the Date() object : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
There are lots of useful methods ....
You can display different date format using Date object in JavaScript.The different date format may be
Year only (YYYY)
Year and month (YYYY-MM)
Complete date (YYYY-MM-DD)
Complete day with day name (YYYY-MM-DD DayName)
Date with different time format
Use the following JavaScript code to display the date on the year only format.
function displayDate(){
var now = new Date();
var year=now.getFullYear();
date.innerHTML=year
}
window.onload=displayDate;
<div id="date"></div>
This post will be more helpful to know more about displaying other more date formats: https://www.siteforinfotech.com/2014/03/how-to-display-date-format-in-javascript.html

Convert UTC date time to local date time

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time. I want to convert it to the current user’s browser time zone using JavaScript.
How this can be done using JavaScript or jQuery?
Append 'UTC' to the string before converting it to a date in javascript:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.
More info here:
http://www.w3.org/TR/NOTE-datetime
https://en.wikipedia.org/wiki/ISO_8601
IN this case the server would return '2011-06-29T16:52:48.000Z' which would feed directly into the JS Date object.
var utcDate = '2011-06-29T16:52:48.000Z'; // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);
The localDate will be in the right local time which in my case would be two hours later (DK time).
You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.
This is an universal solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Display the date based on the client local setting:
date.toLocaleString();
For me above solutions didn't work.
With IE the UTC date-time conversion to local is little tricky.
For me, the date-time from web API is '2018-02-15T05:37:26.007' and I wanted to convert as per local timezone so I used below code in JavaScript.
var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');
You should get the (UTC) offset (in minutes) of the client:
var offset = new Date().getTimezoneOffset();
And then do the correspondent adding or substraction to the time you get from the server.
Hope this helps.
This works for me:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
Put this function in your head:
<script type="text/javascript">
function localize(t)
{
var d=new Date(t+" UTC");
document.write(d.toString());
}
</script>
Then generate the following for each date in the body of your page:
<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>
To remove the GMT and time zone, change the following line:
document.write(d.toString().replace(/GMT.*/g,""));
This is a simplified solution based on Adorjan Princ´s answer:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date);
newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return newDate;
}
or simpler (though it mutates the original date):
function convertUTCDateToLocalDate(date) {
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return date;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
After trying a few others posted here without good results, this seemed to work for me:
convertUTCDateToLocalDate: function (date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}
And this works to go the opposite way, from Local Date to UTC:
convertLocalDatetoUTCDate: function(date){
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
Add the time zone at the end, in this case 'UTC':
theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));
after that, use toLocale()* function families to display the date in the correct locale
theDate.toLocaleString(); // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString(); // "9:52:48 AM"
theDate.toLocaleDateString(); // "6/29/2011"
if you have
"2021-12-28T18:00:45.959Z" format
you can use this in js :
// myDateTime is 2021-12-28T18:00:45.959Z
myDate = new Date(myDateTime).toLocaleDateString('en-US');
// myDate is 12/28/2021
myTime = new Date(myDateTime).toLocaleTimeString('en-US');
// myTime is 9:30:45 PM
you just have to put your area string instead of "en-US" (e.g. "fa-IR").
also you can use options for toLocaleTimeString like { hour: '2-digit', minute: '2-digit' }
myTime = new Date(myDateTime).toLocaleTimeString('en-US',{ hour: '2-digit', minute: '2-digit' });
// myTime is 09:30 PM
more information for toLocaleTimeString and toLocaleDateString
Matt's answer is missing the fact that the daylight savings time could be different between Date() and the date time it needs to convert - here is my solution:
function ConvertUTCTimeToLocalTime(UTCDateString)
{
var convertdLocalTime = new Date(UTCDateString);
var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;
convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset );
return convertdLocalTime;
}
And the results in the debugger:
UTCDateString: "2014-02-26T00:00:00"
convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time)
Use this for UTC and Local time convert and vice versa.
//Covert datetime by GMT offset
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
date = new Date(date);
//Local time converted to UTC
console.log("Time: " + date);
var localOffset = date.getTimezoneOffset() * 60000;
var localTime = date.getTime();
if (toUTC) {
date = localTime + localOffset;
} else {
date = localTime - localOffset;
}
date = new Date(date);
console.log("Converted time: " + date);
return date;
}
In case you don't mind usingmoment.js and your time is in UTC just use the following:
moment.utc('6/29/2011 4:52:48 PM').toDate();
if your time is not in utc but any other locale known to you, then use following:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY', 'fr').toDate();
if your time is already in local, then use following:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY');
To me the simplest seemed using
datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());
(i thought the first line could be enough but there are timezones which are off in fractions of hours)
This is what I'm doing to convert UTC to my Local Time:
const dataDate = '2020-09-15 07:08:08'
const utcDate = new Date(dataDate);
const myLocalDate = new Date(Date.UTC(
utcDate.getFullYear(),
utcDate.getMonth(),
utcDate.getDate(),
utcDate.getHours(),
utcDate.getMinutes()
));
document.getElementById("dataDate").innerHTML = dataDate;
document.getElementById("myLocalDate").innerHTML = myLocalDate;
<p>UTC<p>
<p id="dataDate"></p>
<p>Local(GMT +7)<p>
<p id="myLocalDate"></p>
Result: Tue Sep 15 2020 14:08:00 GMT+0700 (Indochina Time).
Using YYYY-MM-DD hh:mm:ss format :
var date = new Date('2011-06-29T16:52:48+00:00');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
For converting from the YYYY-MM-DD hh:mm:ss format, make sure your date follow the ISO 8601 format.
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
Important things to note
You must separate the date and the time by a T, a space will not work in some browsers
You must set the timezone using this format +hh:mm, using a string for a timezone (ex. : 'UTC') will not work in many browsers. +hh:mm represent the offset from the UTC timezone.
A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17".
In angular, (following Hulvej) make a localdate filter:
myFilters.filter('localdate', function () {
return function(input) {
var date = new Date(input + '.000Z');
return date;
};
})
Then, display local time like:
{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}
For me, this works well
if (typeof date === "number") {
time = new Date(date).toLocaleString();
} else if (typeof date === "string"){
time = new Date(`${date} UTC`).toLocaleString();
}
I Answering This If Any one want function that display converted time to specific id element and apply date format string yyyy-mm-dd
here date1 is string and ids is id of element that time going to display.
function convertUTCDateToLocalDate(date1, ids)
{
var newDate = new Date();
var ary = date1.split(" ");
var ary2 = ary[0].split("-");
var ary1 = ary[1].split(":");
var month_short = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
newDate.setUTCHours(parseInt(ary1[0]));
newDate.setUTCMinutes(ary1[1]);
newDate.setUTCSeconds(ary1[2]);
newDate.setUTCFullYear(ary2[0]);
newDate.setUTCMonth(ary2[1]);
newDate.setUTCDate(ary2[2]);
ids = document.getElementById(ids);
ids.innerHTML = " " + newDate.getDate() + "-" + month_short[newDate.getMonth() - 1] + "-" + newDate.getFullYear() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
}
i know that answer has been already accepted but i get here cause of google and i did solve with getting inspiration from accepted answer so i did want to just share it if someone need.
#Adorojan's answer is almost correct. But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa.
Below is the solution which I came with and is working perfectly fine for me:
// Input time in UTC
var inputInUtc = "6/29/2011 4:52:48";
var dateInUtc = new Date(Date.parse(inputInUtc+" UTC"));
//Print date in UTC time
document.write("Date in UTC : " + dateInUtc.toISOString()+"<br>");
var dateInLocalTz = convertUtcToLocalTz(dateInUtc);
//Print date in local time
document.write("Date in Local : " + dateInLocalTz.toISOString());
function convertUtcToLocalTz(dateInUtc) {
//Convert to local timezone
return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000);
}
Based on #digitalbath answer, here is a small function to grab the UTC timestamp and display the local time in a given DOM element (using jQuery for this last part):
https://jsfiddle.net/moriz/6ktb4sv8/1/
<div id="eventTimestamp" class="timeStamp">
</div>
<script type="text/javascript">
// Convert UTC timestamp to local time and display in specified DOM element
function convertAndDisplayUTCtime(date,hour,minutes,elementID) {
var eventDate = new Date(''+date+' '+hour+':'+minutes+':00 UTC');
eventDate.toString();
$('#'+elementID).html(eventDate);
}
convertAndDisplayUTCtime('06/03/2015',16,32,'eventTimestamp');
</script>
You can use momentjs ,moment(date).format() will always give result in local date.
Bonus , you can format in any way you want. For eg.
moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('dddd'); // Friday
moment().format("MMM Do YY");
For more details you can refer Moment js website
this worked well for me with safari/chrome/firefox :
const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);
I believe this is the best solution:
let date = new Date(objDate);
date.setMinutes(date.getTimezoneOffset());
This will update your date by the offset appropriately since it is presented in minutes.
tl;dr (new Date('6/29/2011 4:52:48 PM UTC')).toString()
The source string must specify a time zone or UTC.
One-liner:
(new Date('6/29/2011 4:52:48 PM UTC')).toString()
Result in one of my web browsers:
"Wed Jun 29 2011 09:52:48 GMT-0700 (Pacific Daylight Time)"
This approach even selects standard/daylight time appropriately.
(new Date('1/29/2011 4:52:48 PM UTC')).toString()
Result in my browser:
"Sat Jan 29 2011 08:52:48 GMT-0800 (Pacific Standard Time)"
using dayjs library:
(new Date()).toISOString(); // returns 2021-03-26T09:58:57.156Z (GMT time)
dayjs().format('YYYY-MM-DD HH:mm:ss,SSS'); // returns 2021-03-26 10:58:57,156 (local time)
(in nodejs, you must do before using it: const dayjs = require('dayjs');
in other environtments, read dayjs documentation.)
This works on my side
Option 1: If date format is something like "yyyy-mm-dd" or "yyyy-mm-dd H:n:s", ex: "2021-12-16 06:07:40"
With this format It doesnt really know if its a local format or a UTC time. So since we know that the date is a UTC we have to make sure that JS will know that its a UTC. So we have to set the date as UTC.
function setDateAsUTC(d) {
let date = new Date(d);
return new Date(
Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()
)
);
}
and then use it
let d = "2021-12-16 06:07:40";
setDateAsUTC(d).toLocaleString();
// output: 12/16/2021, 6:07:40 AM
Options 2: If UTC date format is ISO-8601. Mostly servers timestampz format are in ISO-8601 ex: '2011-06-29T16:52:48.000Z'. With this we can just pass it to the date function and toLocaleString() function.
let newDate = "2011-06-29T16:52:48.000Z"
new Date(newDate).toLocaleString();
//output: 6/29/2011, 4:52:48 PM
In JavaScript I used:
var updaated_time= "2022-10-25T06:47:42.000Z"
{{updaated_time | date: 'dd-MM-yyyy HH:mm'}} //output: 26-10-2022 12:00
I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/Y H:i:s (like the PHP date function) format:
getTimezoneDate = function ( e ) {
function p(s) { return (s < 10) ? '0' + s : s; }
var t = new Date(0);
t.setUTCSeconds(e);
var d = p(t.getDate()),
m = p(t.getMonth()+1),
Y = p(t.getFullYear()),
H = p(t.getHours()),
i = p(t.getMinutes()),
s = p(t.getSeconds());
d = [d, m, Y].join('/') + ' ' + [H, i, s].join(':');
return d;
};

Regarding JavaScript new Date() and Date.parse()

var exampleDate='23-12-2010 23:12:00';
I want to convert above string into a date and have tried a couple things:
var date = new Date(exampleDate); //returns invalid Date
var date1 = Date.parse(exampleDate); //returns NAN
This code is running fine in IE and Opera, but date is returning me an invalid Date and date1 is returning NAN in Firefox. What should I do?
The string in your example is not in any of the standard formats recognized by browsers. The ECMAScript specification requires browsers to be able to parse only one standard format:
The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
Also included are “date-times” which may be any combination of the above.
If the String does not conform to that format the function may fall back to any
implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates
containing illegal element values in the format String shall cause Date.parse to return NaN.
So in your example, using 2010-12-23T23:12:00 is the only string guaranteed to work. In practice, most browsers also allow dates of the format DD Month YYYY or Month DD, YYYY, so strings like 23 Dec 2010 and Dec 23, 2010 could also work.
Above format is only supported in IE and Chrome.
so try with another formats. following are some formats and there supporting browsers.
<script type="text/javascript">
//var dateString = "03/20/2008"; // mm/dd/yyyy [IE, FF]
var dateString = "2008/03/20"; // yyyy/mm/dd [IE, FF]
// var dateString = "03-20-2008"; // mm-dd-yyyy [IE, Chrome]
// var dateString = "March 20, 2008"; // mmmm dd, yyyy [IE, FF]
// var dateString = "Mar 20, 2008"; // mmm dd, yyyy [IE, FF]
// Initalize the Date object by passing the date string variable
var myDate = new Date(dateString);
alert(myDate);
</script>
You could parse it manually with a regular expression then call the date constructor with the date elements, as such:
var parseDate = function(s) {
var re = /^(\d\d)-(\d\d)-(\d{4}) (\d\d):(\d\d):(\d\d)$/;
var m = re.exec(s);
return m ? new Date(m[3], m[2]-1, m[1], m[4], m[5], m[6]) : null;
};
var dateStr = '23-12-2010 23:12:00';
parseDate(dateStr).toString(); //=> Thu Dec 23 2010 23:12:00 GMT-0800
JavaScript should support conversion at least from the following dateStrings:
* yyyy/MM/dd
* MM/dd/yyyy
* MMMM dd, yyyy
* MMM dd, yyyy
Try with:
var exampleDate='12/23/2010 23:12:00';
var date = new Date(exampleDate);
Use datejs and this code:
var exampleDate='23-12-2010 23:12:00';
var myDate = Date.parseExact(exampleDate, 'dd-MM-yyyy hh:mm:ss');
myDate should be a correctly constructed Date object.
Just use in this format:
var exampleDate='2010-12-23 23:12:00';
#casablanca has a good answer but it's been 10+ years and this still has a lot of weight in Google so I thought I'd update with a new answer.
TL;DR
// Use an ISO or Unix time string to generate `Month DD, YYYY`
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${newDate.getDate()}, ${newDate.getFullYear()}`
// yields: December, 23 2010 (if you want date suffix, read until the end)
Background: Dates come in a lot of formats, but you're mostly going to receive:
An ISO 8601 format date (YYYY-MM-DDTHH:mm:ss.sssZ) where Z is a UTC timezone offset. You might also get a subset of this (ie, YYYY-MM-DD)
Unix timestamp format date (1539734400), where the number is literally the total amount of milliseconds since the beginning of Unix time, Jan 1st 1970.
Basics: JS has a built-in Date prototype that accepts ISO 8601 and derivatives (of just time or just date). You can instantiate with new Date and return a date object OR you can use the Date.parse() method to return a Unix timestamp.
const dateObj = new Date('23-12-2010:23:12:00') // returns date object
const dateDateOnly = new Date('23-12-2010') // returns date object
const dateTimeOnly = new Date('23:12:00') // returns date object
const dateString = Date.parse('23-12-2010:23:12:00') // returns Unix timestamp string
You can also break the date into 7 parameters: the year, the month (starting from 0), the day, the hour, the minutes, seconds and milliseconds with the time zone offset - NOTE, I've used the multi-params approach only once in my career. Since I'm in Texas I get, UTC-5 (Central Time) when I run the following:
const dateByParam = new Date(2021, 2, 26, 13, 50, 13, 30) // Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time)
New-ish Stuff toLocaleString: Typically, the return from the Date object is still pretty dense like our last example (Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time) so additional methods have been added to help developers.
Typically with a date, I want something like March 21st, 2021 - the day and year have been easy to get for a long time:
// Assuming myDate is a JS Date object...
myDate.getDate() // date on the calendar, ie 22
myDate.getDay() // day of the week, where 0 means Sunday, 1 means monday, etc
myDate.getFullYear() // 4 digit year, ie, 2021
But I've always had to build a function to turn getDay into January, February, March, not anymore. toLocaleString() gives you some new superpowers. You can pass it two params, a string for region (ie, en-us) and an object with what you want back (ie, { month: 'long' }). This helps internationalize the response, if need be.
// Again, assuming myDate is a JS Date object...
myDate.toLocaleString('en-us', { month: 'long' } ) // March
Date Suffix I've still seen no built-in way to get the suffix for a date, like th, st, so I built this utility function that uses the modulus % operator to check the divisor of each day number and apply the right suffix (aimed at an American audience but might be the same elsewhere?).
/**
* setDateSuffix()
*
* Desc: Takes two digit date, adds 'st', 'nd', 'rd', etc
*
* #param { integer } num - a number date
*/
export const setDateSuffix = (num) => {
const j = num % 10,
k = num % 100
if (j === 1 && k !== 11) {
return num + "st";
}
if (j === 2 && k !== 12) {
return num + "nd";
}
if (j === 3 && k !== 13) {
return num + "rd";
}
return num + "th";
}
Altogether now.. Long winded way of getting here, but if I am given an ISO or Unix date and I want Month DDth, YYYY, this is what I run:
// setDateSuffix IS NOT PART OF BUILT-IN JS!
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${setDateSuffix(newDate.getDate())}, ${newDate.getFullYear()}`
// yields: December 23rd, 2010
Note - all of this will likely change, hopefully for the better, when temporal becomes a reality in JS: https://github.com/tc39/proposal-temporal. Look forward to somebody's 2030 update of this post!

Categories

Resources