how to display the date in this below format using jQuery.
Thursday, January 08, 2013
I saw some plugins but wondering if there is a way without using any plugin.
Please advise if there is a straightforward answer using JavaScript, that's fine too.
The simplest answer is to use:
date.toLocaleDateString()
But, it will use the locale defined by the user's system. The American/English locale fitting your desired output. (I'm not sure about other locales and how they format dates).
So, if you want the date string to always be in that format, this will not be the best answer for you. But, if you want the date to match the user's locale, this answer is the simplest and most correct. :)
http://jsfiddle.net/SyjpS/
var date = new Date();
console.log(date.toLocaleDateString()); // Tuesday, January 08, 2013 (on my machine)
EDIT — If you're asking how to change the calendar so that today is Thursday instead of Tuesday, you may need to talk to Caesar about adjusting the calendar realignment. For this, you'll need a time machine. I suggest that you seek out the Doctor, but he may not be willing to change history willy nilly.
Here's a quick/simple example of what you're asking for:
EDIT - I've update the code for reuse and include the day 0 padding change.
var d = new Date();
console.log(formatDate(d));
function formatDate(d){
var months = ["Januaray", "February", "March"]; //you would need to include the rest
var days = ["Sunday", "Monday", "Tuesday"];//you would need to include the rest
return days[d.getDay()] + ", " + months[d.getMonth()] + " " + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + ", " + d.getFullYear();
}
Output for today: Tuesday, Januaray 08, 2013
EXAMPLE
Simply use DateJS not to reinvent the wheel.
You may read the API documentation here:
http://code.google.com/p/datejs/wiki/APIDocumentation
The date methods allow you to retrieve all of the different parts of the date and time as numerical values. In the case of the month of the year and the day of the week, the number that is provided is one less than you would normally expect. The reason for this is that the most common use for these values is to use it to look up the name of the month or day from an array and as arrays in JavaScript are numbered from zero, providing the numbers like that reduces the amount of code needed to do the name lookups.
We can go one better than just doing this lookup using the retrieved values though. What we can do is to add extra methods to the Date object to allow us to retrieve the month and day names whenever we want the exact same way that we retrieve any of the other information about the date.
The probable reason why the following methods are not built into the JavaScript language itself is that they are language dependent and need to have different values substituted into the code depending on the language that you want to display the month and day in. For the purpose of showing you how to code this I am going to use the Emglish names for the months and days. If you want to display dates in a different language you will need to substitute the names from that language for their English equivalents.
What we are going to do is to add getMonthName() and getDayName() methods to all our dates so that we can get the month name or day name by calling these new methods directly instead of having to call getMonth() or getDay() and then do an array lookup of the corresponding name. What we are actually doing is building the required array lookups into the new methods so that we can automatically get the correct names for any of our date objects simply by calling the appropriate method.
We don't neeed all that much code to do this. All you need to do to add the getMonthName() and getDayName() methods to all of the date objects that you use is to add the following short piece of code to the very top of the javaScript code attached to the head of your page. Any subsequent processing of date objects will then be able to use these methods.
Date.prototype.getMonthName = function() {
var m = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
return m[this.getMonth()];
}
Date.prototype.getDayName = function() {
var d = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
return d[this.getDay()];
}
So now with that in place we can display today's date on the page using those new methods in addition to the existing ones. For example we might use the following to get the full date and display it using an alert:
var today = new Date;
alert((today.getDayName() + ', ' + today.getDate() + ' ' + today.getMonthName() + ', ' + today.getFullYear());
Alternatively, we can just retrieve the current month June and day of the week Sunday and use them however we want just the same as for any of the other parts of the date.
function disp() {
var today = new Date;
document.getElementById('mth').innerHTML = today.getMonthName();
document.getElementById('dow').innerHTML = today.getDayName();
}
Related
I'm using Javascript's toLocalDateString method to get the date of the user on their local system time.
However the output format of the function is different across windows and mac (using chrome browsers on both):
On Windows
On Mac
As you can see on windows we get format m-dd-yyyy whereas on mac it's dd-mm-yyyy. This is causing issues in my code as I need to display it in a common format using substr on the resulting output and fetching year, date and month separately.
Is there any way to force this to output in one particular format only or is there any other reliable way to get system's local date (I only need date not the time)
You will have to pass locals argument as below:
// US English uses month-day-year order
console.log(date.toLocaleDateString('en-US'))
// British English uses day-month-year order
console.log(date.toLocaleDateString('en-GB'))
Check reference link -
toLocaleDateString
There is no guarantee whatsoever how the output of toLocaleDateString() will look on a particular browser on a particular system. So if you need a specific format, you must either create it yourself or use some library.
If you just need separate year, day and month of the current date, why not just use the respective methods on the Date() object?
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() +1; //month count is 0-based
const day = today.getDate();
var date= new Date();
var formatDate;
if(navigator.appVersion.indexOf("Win") != -1){
formatDate= date.toLocaleDateString('en-GB');
}
else{
formatDate= date.toLocaleDateString();
}
console.log(formatDate);
I bumped into a situation where I'm getting a string indicating only the month and year of a date, and I need to create a Date object out of it. If I pass just the string, e.g. "February 2020" into a Date constructor, I strangely get back the the day of the previous month, i.e. in this case 2020-31-01. Thus, I need to always add 1 day to get the proper month in the Date object.
Here is the code to replicate:
var date_str = "February 2020";
var dt = new Date(date_str)
console.log(dt) // Returns : 2020-01-31T23:00:00.000Z (????)
dt.setDate(dt.getDate() + 1);
console.log(dt) // Returns : 2020-02-01T23:00:00.000Z
Any idea what the logic is behind this rather strange behaviour, or do I miss something here?
Update
Have accepted the first answer as being relevant, thus the main question is solved. However, just to add to the confusion: the code snippet I included runs as described with node. Using EXACTLY the same logic in a Vue.js application return the correct Date. Very strange!
"February 2020" is not a valid input according to the specification thus you should not rely on it to work.
You should convert your input to one that is according to spec and then decide whether you need local time or UTC.
Handling time(zones) is one of the hardest things in JavaScript and I strongly recommend that you do not try to reinvent the wheel here yourself as it is really easy to mess up.
Libraries like momentjs can help you here.
Actually you are passing February 2020 into the date Constructor , and its assumes the
date as 1 February 2020 thus it give the output as its UTC date which may be previous
day depending on your region
Use moment.js library, it will give perfect.
moment("February 2020").format('L')
"02/01/2020"
I'm using d3 v3 to parse some intraday data that has the following format:
time,value
09:00,1
09:05,2
09:10,3
...
So I set up a parsing variable like so:
var parseTime = d3.time.format("%H:%M").parse;
And I map the data within the scope of the csv call:
d3.csv("my_data.csv", function(error, rawData) {
var data = rawData.map(function(d) {
return {y_value: +d.value, date: parseTime(d.time)}
});
console.log(data)
}
In the console, I get something strange. Instead of only the hour, I get the full-fledged date, day of the week, month, even time zone.
data->
array[79]
0:Object->
date: Mon Jan 01 1900 09:00:00 GMT+0000
y_value: 1
Do dates need to be this complete? I suppose that could explain why I wound up with monday Jan. 1st, seems like a default of sorts. However, according to d3 time documentation, "%H:%M" is used for hours and minutes. And I could have sworn I did that much correct.
I know something is not quite right because my line graph is throwing the error:
error: <path> attribute d: expected number "MNaN"
My best guess is that the date is over-specified and the axis() is expecting an hour format.
My Question is: Why isn't my data being parsed as hour only? Should I change this from the parsing end? If that's not an option, can I have the x domain read a portion of the date (the hour and minute portion)?
Update: Here is a minimal block for further illustration of my plight.
When you say...
why isn't my data being parsed as hour only?
... it becomes evident that there is a basic misunderstanding here. Let's clarify it.
What is a date?
Simply put, a date is a moment in time. It can be now, or two months ago, or the day my son was born, or next Christmas, or the moment Socrates drank the hemlock. It does'n matter. What is important to understand is that all those dates have a century, a decade, a year, a month, a day, an hour, a minute, a second, a millisecond etc... (of course, those names are conventions that can be changed).
Therefore, it makes little sense having a date with just the hour, or just the hour and the minute.
Parsing and formating
When you parse a string, you create a date object. As we explained above, that date object corresponds to a moment in time, and it will have year, month, hour, timezone etc... If the string itself lacks some information, as year for instance, it will default to some value.
Look at this demo, we will parse a string into a date object, using the correct specifier:
var string = "09:00";
var parser = d3.timeParse("%H:%M");
var date = parser(string);
console.log("The date object is: " + date);
<script src="https://d3js.org/d3.v4.min.js"></script>
As you can see, we have a date object now. By the way, you can see that it defaults to a given year (1900), a given month (January), and so on...
However, in your chart, you don't need to show the entire object, that is, all the information regarding that moment in time. You can show just hour and minute, for instance. We will format that date.
Have a look:
var string = "09:00";
var parser = d3.timeParse("%H:%M");
var format = d3.timeFormat("%H:%M");
var date = parser(string);
console.log("The date object is: " + date);
console.log("The formatted date is: " + format(date));
<script src="https://d3js.org/d3.v4.min.js"></script>
That formatted date is useful for creating axes, tooltips, texts etc..., that is, showing the date you have without showing all its details. You can choose what information you want to show to the user (just the year, or just the month, or maybe day-month-year, whatever).
That's the difference between parsing and formatting.
Why using a formatter?
To finalise, you may ask: why am I using a formatter, if I will end up having the same thing I had at the beginning?
The answer is: you don't have the same thing. Now you have a date, not a string. And, using a date with a time scale, you can accomodate daylight savings, leap years, February with only 28 days, that is, a bunch of things that are impossible to do with a simple string.
PS: The demos above use D3 v4.
EDIT: After your update we can easily see the problem with your code: you have to pass an array to range().
var xScale = d3.time.scale().range([0,width]);
Here is the updated bl.ocks: http://bl.ocks.org/anonymous/a05e15339f7792f175d2bcebccf6bbed/7f23db481f1308eb0d5a1834f7cbc0b17d948167
I'm using moment-with-locales.min.js for date manipulation and I need to format as the user leaves the textboxes. Because locales are an issue, I'm trying to use moment to do the formatting. However, I'm running into a problem and I'm not sure if I'm doing it wrong or what.
If the user types in something like '2/2/12' and I try to do moment('2/2/12', 'l'), using the 'l' for short date based on locale, it formats it into '2/2/0012'. That in itself seems broken.
If I try to format with moment('2/2/12', 'M/d/yyyy'), as seen in the JSFiddle below, it changes it to '2/1/2014'. It always bumps it down to the first day of the month and makes it the current year.
Here's the JSFiddle I was using.
moment.locale('en-US');
var parsed = moment('2/2/12', 'M/d/yyyy');
if (moment(parsed).isValid()) {
var d = new moment(parsed, 'l');
alert('Pass: ' + d.format('l'));
} else {
alert('Fail: ' + parsed);
}
I'd appreciate and help.
You should use "D" ("d" is day of week).
As for the year, according to the docs, «Two digit year parser by default assumes years above 68 to be in the 1900's and below in the 2000's.» so I'm guessing (and experimentation seems to confirm it) that if you use the 4 digit format ("YYYY") it'll assume you are passing in the year 12 and not 2012. If you use "YY" it'll print 2012 correctly.
So, to summarize, the format "M/D/YY" should do what you want.
I understand that the datepicker (I'm using AngularStrap's datepicker) is "behind" a day because of how dates are calculated in javascript. My problem is, how to I get it to not take the timezone into consideration and just stick with the entered date... no adjustments?
I select February 1, 2014 in the datepicker. My value on the screen is 2/1/2014 and I want that value to be saved. However, the datepicker turns this into Fri Jan 31 2014 19:00:00 GMT-0500 (EST) apparently because it subtracts the 5 hours for my timezone from the entered date. I do not want this. If I enter 2/1/2014 I want that date, regardless of the timezone.
What is the best way to intercept/change/edit this value so that entering 2/1/2014 gives me exactly that date... no conversion for timezone? Should I modify the datepicker code itself (this seems like a bad idea)? Should I change the value myself prior to sending it to the backend by adding in some sort of offset? If so, how do you add time to a value that console displays as Fri Jan 31 2014 19:00:00 GMT-0500 (EST)?
I solved this problem with a custom directive https://gist.github.com/weberste/354a3f0a9ea58e0ea0de
It's for Angular Bootstrap datepicker but I guess it should work for AngularStrap datepicker as well since it only depends on the corresponding ngModel rather than the datepicker itself.
Essentially, I'm reformatting the value whenever a date is selected on the datepicker (this value, a yyyy-mm-dd formatted string, will be stored on the model) and whenever the model is accessed to populate the view, I need to wrap it in a Date object again so datepicker handles it properly.
In other words, it is exactly doing the interceptions that you ask for in your question.
I know this thread is kind of old but since there is no accepted solution I thought I'd offer what finally worked for me after lots of messing around:
The issue in my case was that the datepicker was using the wrong timezone so when I would try to edit an event, the wrong date would display even though the correct date was stored in the db. The following fixed it for me:
var evDate = new Date(data.eventDate); //data.eventDate is the date string
evDate.setMinutes(evDate.getMinutes() + evDate.getTimezoneOffset());
$scope.eventInfo.eventDate = evDate;
I found this solution here: https://github.com/angular-ui/bootstrap/issues/2628
If you don't mind loading another resource, then I would recommend using MomentJS as it takes the pain out of dates in JavaScript. You can do something like `moment(datepicker value).local()' to get the date without the timezone offset.
http://momentjs.com/docs/#/manipulating/local/
I have found a way. convert that date to string first. here is the code.
var SelectDate = $scope.GetFormattedDate(Date.parse($("#Date").datepicker("getDate")));
$scope.GetFormattedDate = function (CalDate) {
var re = /-?\d+/;
var WDate = CalDate.toString();
var m = re.exec(WDate);
var lastDate = new Date(parseInt(m[0]));
var mm = lastDate.getMonth() + 1;
var dd = lastDate.getDate();
var yyyy = lastDate.getFullYear();
var formattedDate = mm + '/' + dd + '/' + yyyy;
return formattedDate;
}
Now Pass SelectDate to your controller. bingo problem has been resolved :)
Guys if you are experiencing this problem is because probably,you are reactivily ,puting data in boostrap datepicker.This solution worked for me.
First you check if date is null
dateBegin===null?dateBegin=null:dateBegin = new Date(formatDate(dateBegin,'yyyy-MM-dd','en'));
**if is null you set its value to null which you are going putt in your Form Group and in Form Group Control
this.ugovorForm = new FormGroup({'dateBegin':new FormControl(dateBegin)})
else you will set Date and format it using formatDate property , provided by Angular.I was struguling with this problem for along time.And its because I'm loading dates from Database.Good Luck;