Javascript, translate date using array - javascript

Due to the language barrier I am unable to find an answer to a problem I'm having.
Using 2 arrays in JavaScript I need to translate a date.
var months =['january','february','march','april','may','june','july','august','september','october'.'november','december'];
var weekday = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'];
Using this I am supposed to turn for example:
Mon Oct 28 2018 14:41:20 GMT+0100
into
Monday 28 October 2018
My apologies for this likely being a repost of a question that has been answered previously, but as I previously mentioned I was unable to find it.

Use moment.js
moment(new Date('Mon Oct 28 2018 14:41:20 GMT+0100')).format('dddd DD MMMM YYYY')

You don't need external libraries in order to achieve your requirement.
You just need to use some Date functions.
var months = ['january','february','march','april','may','june','july','august','september','october','november','december'];
var weekday = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'];
var date=new Date();
console.log(getDate(date));
function getDate(date){
return [
weekday[date.getDay()],
date.getDate(),
months[date.getMonth()],
date.getFullYear()
].join(' ');
}

If you want to vanilla javascript solution:
A simple solution (if you can forgo the exact full month name):
var date = new Date("Mon Oct 28 2018 14:41:20 GMT+0100");
console.log(date.toDateString());
Or
Pass some options into toLocaleDateString:
var date = new Date("Mon Oct 28 2018 14:41:20 GMT+0100");
console.log(date.toLocaleDateString("en-US", {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
}))
Check MDN Date documentation here.

Related

Format JS date.toLocaleString differently

var date = new Date();
date.setDate(date.getDate() + 1)
console.log(`streak=0; expires=${date.toLocaleString('en-us', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}`);
In my output, I get
streak=0; expires=Sunday, January 2, 2022
My question is:
How can I format the date like this:
Thu, 18 Dec 2013 12:00:00 UTC
(12 and UTC don't need to be included)
I want the date number to go first then the month, not the other way around.
I am doing this because I need it to be formatted like that for a cookie:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
(w3schools)
Tell me if that's not how you use cookies.

Convert UTC time to Browser's local time in angularjs/javascript

From the server I am getting a DateTime in this format: 2019-07-11T05:33:53.45 and it is in UTC time.
I want to convert it to the current user’s browser time using JavaScript in the format like 11th July 2019 11:03 AM which is UTC+0530 for Indian time for given time(2019-07-11T05:33:53.45).
I have tried Intl.DateTimeFormat and also other JavaScript date time functions eg. toLocaleString. But I am getting the time in UTC format only. When I get the time as what I want UTC+0530 is also attached, which I don't want.
let d = new Date(date_from_server);
let options= { year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false };
let ddmmmyy= new Intl.DateTimeFormat('default', options).format(d);
This is one of the solution I tried. I have tried other methods also, but didn't succeed.
eg. let ddmmmyy = d.toLocaleString();
I want the time as per User's current browser timezone and in the specified format(11th July 2019 11:03 AM IST).
How can I achieve it? Please help.
You need to replace the T in the date string and also append UTC.
Then you need to remove GMT and anything after that in the result:
var dateString = "2019-07-11T05:33:53.45".replace('T', ' ') + " UTC"; // or + "Z" instead of + " UTC";
var dateObj = new Date(dateString);
var localDateString = dateObj.toString().replace(/GMT.*/g,"");
console.log(localDateString);
Try this:
var date = new Date('2019-08-14 17:00:34 UTC');
date.toString(); // outputs "Wed Aug 14 2019 13:00:34 GMT-0400 (Eastern Daylight Time)"

Function returns incorrect month depending on order of statements

Does anyone have any thoughts on why this might have happened? Today, I found that a date conversion function I wrote started returning the wrong month. For instance, when attempting to convert "2017-06-02" to "Fri Jun 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)", it actually returned July instead of June. When I re-arranged the order of some of the statements in the function, the correct date was finally returned. This code has been in place for many months, so this spontaneous...maybe due to the current month changing, as today is 5/31/17? This might only be broken when ran on todays date, or end-of-month? (I'm sure there's a better way to convert dates, but here's the code in question anyway):
<!doctype html>
<body onload="testDate()">
<div id="resultbad"></div>
<div id="resultgood"></div>
<script>
function testDate() {
document.getElementById("resultbad").innerHTML = "Bad Result: Converting 2017-06-02 returns: " + badDate("2017-06-02");
//returns: Bad Result: Converting 2017-06-02 returns: Sun Jul 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)
document.getElementById("resultgood").innerHTML = "Good Result: Converting 2017-06-02 returns: " + goodDate("2017-06-02");
//returns: Good Result: Converting 2017-06-02 returns: Fri Jun 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)
}
function badDate(d) {
var td = d.split('-');
var nd = new Date();
//originally ordered: Year, Month then Day
nd.setFullYear(td[0]);
nd.setMonth(td[1] - 1);
nd.setDate(td[2]);
//set time
nd.setHours(0);
nd.setMinutes(0,0,0);
return nd;
}
function goodDate(d) {
var td = d.split('-');
var nd = new Date();
//new order: Day, Month then Year
nd.setDate(td[2]);
nd.setMonth(td[1] - 1);
nd.setFullYear(td[0]);
//set time
nd.setHours(0);
nd.setMinutes(0,0,0);
return nd;
}
</script>
</body>
This code overrides the date elements based on today's date. So, if you are running the code on the 31st day of the month, the "bad" version of this code will overwrite the month first, and if that month only has 30 days, it will roll over to the next month.
Basically, after setMonth but before setDate, you are trying to create the date June 31, 2017, which JS will convert for you into July 1, 2017.
Instead, do this as one call:
new Date(td[0], td[1]-1, td[2], 0, 0, 0, 0)
You figured out the problem fairly well - it has to do with today being the 31st of the month.
The issue is that new Date() creates a date object with the fields filled in. You're then changing those fields one by one.
So right now we can think of it as having a pseudo-structure like this, remembering that month is 0-based:
{
year: 2017
month: 4
date: 31
}
when you call setMonth(), you're just changing the month field, so you'd think for June it would set it to
{
year: 2017
month: 5
date: 31
}
but it knows there aren't 31 days in June. The 31st "day" of June would be the 1st of July. So it helps you out and adjusts it to
{
year: 2017
month: 6
date: 1
}
You're then setting the date to the 2nd with setDate():
{
year: 2017
month: 6
date: 2
}
In the function that works, you're setting the date before the month, so you're not having it recompute what the day is in case you've specified a date that is larger than the number of days in the month.

Remove time from GMT time format

I am getting a date that comes in GMT format, Fri, 18 Oct 2013 11:38:23 GMT. The problem is that the time is messing up the timeline that I am using.
How can I strip out everything except for the actual date?
If you want to keep using Date and not String you could do this:
var d=new Date(); //your date object
console.log(new Date(d.setHours(0,0,0,0)));
-PS, you don't need a new Date object, it's just an example in case you want to log it to the console.
http://www.w3schools.com/jsref/jsref_sethours.asp
Like this:
var dateString = 'Mon Jan 12 00:00:00 GMT 2015';
dateString = new Date(dateString).toUTCString();
dateString = dateString.split(' ').slice(0, 4).join(' ');
console.log(dateString);
I'm using this workaround :
// d being your current date with wrong times
new Date(d.getFullYear(), d.getMonth(), d.getDate())
You could use Moment.js, a library that provides many helper functions to validate, manipulate, display and format dates and times in JavaScript.
Using Moment.js lib:
var dateString = new Date('Mon Jan 12 00:00:00 GMT 2015');
moment(dateString).format('YYYY-MM-DD HH:mm');
Or simplified:
moment('Mon Jan 12 00:00:00 GMT 2015').format('YYYY-MM-DD HH:mm')
Well,
Here is my Solution
let dateString = 'Mon May 25 01:07:00 GMT 2020';
let dateObj = new Date(dateString);
console.log(dateObj.toDateString());
// outputs Mon May 25 2020
See its documentation on MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
Just cut it with substring:
var str = 'Fri, 18 Oct 2013 11:38:23 GMT';
str = str.substring(0,tomorrow.toLocaleString().indexOf(':')-3);
In this case you can just manipulate your string without the use of a Date object.
var dateTime = 'Fri, 18 Oct 2013 11:38:23 GMT',
date = dateTime.split(' ', 4).join(' ');
document.body.appendChild(document.createTextNode(date));
You can first convert the date to String:
String dateString = String.valueOf(date);
Then apply substring to the String:
dateString.substring(4, 11) + dateString.substring(30);
You need to take care as converting date to String will actually change the date format as well.

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories