I have a date which looks like:
30 Apr 2015
How do I parse and display the date like this (without Moment.js)?
2015-04-31 (or YYYY-mm-dd)
The easiest thing to do might be to use moment.js.
If you prefer rolling your own solution in vanilla JS, this will work:
var padZero = function (integer) {
return integer < 10 ? '0' + integer : '' + integer
};
var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' +
(padZero(myDate.getMonth()+1)) + '-' +
(padZero(myDate.getDate()));
console.log(myDateString); // 2015-04-30
The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :)
var x = new Date("30 Apr 2015");
Formatting the date is a little trickier. You have a few options. Date natively supports several output methods (.toDateString(), .toLocaleDateString(), etc) but none of them match the format you've given. It does, however, allow you to individually select the day, month and year values for the date. So, you can assemble them manually:
console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())
Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate()).
However, your better choice is to take a look at moment.js, which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists.
Use moment.js
Convert your date like this:
var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30
DEMO
you can do that easy with
//define Date
var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
var months = {
Jan:'01',
Feb:'02',
Mar:'03',
Apr:'04',
May:'05'
};
// split our Date and rearrange as yyyy-mm-dd
var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
alert(reform);// return 2015-04-31
Related
I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));
Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.
Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.
I get a response from a service and when the service returns it returns with a created server GMT date. The issue arises when I want to display the local date ex: 5-22-2016 I want to change the time to my local computer.
my response looks something like this:
createdDate: "2016-04-22 16:48 PM GMT"
description: "File Upload Success"
fileGuid:"62e7250c-d5ed-41e2-b5b2-4600094d9a7c"
fileSize:"191429"
There are 90 different objects in my array.
I am trying to use _each which iterates through all of my key value pairs:
_.each(data, function(value, key) {
console.log(key, value);
var strDateTime = value.createdDate;
var myDate = new Date(strDateTime);
data[key].createdDate = (myDate.toLocaleString()).split(',')[0];
console.log("data", data)
But it is working for some of created dates and the others are returning invalid any suggestions
According to ECMA-262 5.1 15.9.1.15 Date Time String Format, seems some of your data doesn't in the right format.
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ.
So a better solution would be using the moment.js.
With moment.js you can update your code into,
moment('2016-5-5').toLocaleString() //'Tue May 05 2015 00:00:00 GMT+0800'
Also, for only the showing purpose, there is an angular directive version, angular-moment.
Hope this would help. :)
Thx for the notice from #RobG, I just replaced the MDN with ECMA-262.
and for moment("2016-04-22 16:48 PM GMT"), you can see from the picture below,
You should manually parse date strings. A library can help, but if you only have one format, a bespoke parsing function is fairly trivial.
If the dates are always GMT and in the format '2016-04-22 16:48 PM GMT', a function like the following may suit.
If you want the output string in a particular format, you can use toISOString, which returns a string in ISO 8601 format with GMT time zone, or you can write a small formatting function to generate the format you require.
var s = '2016-04-22 16:48 PM GMT';
// Return a Date given a string in format 2016-04-22 16:48 PM GMT
function parseSpecial(s) {
var b = s.split(/[-\s:]/);
var h = (b[3]%12) + (/pm/i.test(s)? 12: 0);
return new Date(Date.UTC(b[0], b[1]-1, b[2], h, b[4]));
}
// Return a string in format mm/dd/yyyy hh:ss a given a date
function myFormat(date) {
function z(n){return (n<10?'0':'') + n}
var h = date.getHours();
var ap = h > 11? 'pm' : 'am';
h = h%12 || 12;
return z(date.getMonth() + 1) + '/' + z(date.getDate()) + '/' +
date.getFullYear() + ' ' + z(h) + ':' + z(date.getMinutes()) +
' ' + ap;
}
var d = parseSpecial(s);
document.write(s + // Original string
'<br>' + d.toISOString() + // As ISO 9601 long format string
'<br>' + myFormat(d) // As local date and time
+ ' (your local date and time equivalent)');
You an use a library to do all of the above, but whether one is necessary or not is up to you. For example, using moment.js, you'd do:
// Parse the string, passing the format
var s = '2016-04-22 16:48 PM GMT';
var d = moment(s.replace('GMT','Z'), 'YYYY-MM-DD hh:mm a Z');
// Create a string for local time in the required format
console.log(d.format('DD/MM/YYYY hh:mm a'));
How would I go about converting following date:
Thu Feb 18 12:25:00 SGT 2016
into a format like '2016-02-18'?
I know,
That, using a new Date(Date.parse('...')), with calls, will help me get it. But the problem being timezone part (SGT).
I dont want to use any libraries out there.
What would be the effective way to go about this?
Any help is appreciated!
PS:
Ok, I have tried
new Date(Date.parse('Thu Feb 18 12:25:00 SGT 2016'))
but of-course, it is going to me 'invalid date' error.
I guess I should wait for you to post some code, but here's an example. It splits the string into parts, converts the month name to a number, then outputs the bits you want in the order you want. The slice on the month name is just in case you want to use the full month name, but maybe that's unnecessary:
function reformatDate(s){
var b = s.split(/[\s:]/);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
return b[7] + '/' + months[b[1].toLowerCase().slice(0,3)] + '/' + ('0'+b[2]).slice(-2);
}
document.write(reformatDate('Thu Feb 18 12:25:00 SGT 2016'));
That format date string (y/m/d) isn't consistent with any standard that I know of and likely will not be parsed by most browsers.
Why not just take the individual components of the date object and build a string from them?
full_date = new Date();
formatted_date_string = full_date.getFullYear() + "-" + (full_date.getMonth()+1) + "-" + full_date.getDate();
I'll leave it to you to sort out the leading 0s on the day and month.
var input="Thu Feb 18 12:25:00 SGT 2016";
var ar=input.split(" ");
var months = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"};
console.log(ar[ar.length-1]+"-"+months[ar[1]]+"-"+ar[2]);
Try this code no date parsing required. Please check on console for result.
var date = "Thu Feb 18 12:25:00 SGT 2016";
date = date.replace("SGT","GMT+0800") // replaces SGT with GMT+0800 because
singapore time is 8 hrs ahead than GMT timezone
var newdate = new Date(Date.parse(date))
var requiredDate = newdate.toLocaleDateString()
I have a json response like this :
{
"NO_INSPECTION": "55",
"NO_SURAT": "00055",
"DATE_OF_DESCRIPTION": "2015-12-21 03:08:24"
}
How can I convert the data in "DATE_OF_DESCRIPTION" Into date and time. Date should be dd-mm-yyy format and time should be in HH:mm format. (A sample value of DATE_OF_DESCRIPTION is 2015-12-21 03:08:24)
I have tried new Date(response.DATE_OF_DESCRIPTION); but no success. How can I achieve this?
Without the use of other libraries and assuming the output will always be zero-padded and the same length, I would do this:
var response = {
DATE_OF_DESCRIPTION: "2015-12-21 03:08:24"
}
var raw = response.DATE_OF_DESCRIPTION;
var datePart = raw.split(' ')[0];
var timePart = raw.split(' ')[1];
var year = datePart.substring(0, 4);
var month = datePart.substring(5, 7);
var day = datePart.substring(8, 10);
var hours = timePart.substring(0, 2);
var minutes = timePart.substring(3, 5);
// NOTE: Month is 0 indexed
var date = new Date(year, month - 1, day);
var dateTime = new Date(year, month - 1, day, hours, minutes);
console.log(date);
console.log(dateTime);
This gives the output
Mon Dec 21 2015 00:00:00 GMT+1000 (E. Australia Standard Time)
Mon Dec 21 2015 03:08:00 GMT+1000 (E. Australia Standard Time)
(I'm from Australia, so your timezone will vary)
JavaScript has a fixed date format and you can change it, thus the Date object won't help you this time. As I see it, you want to split that date, so it's pretty easy if you provide it in this format "dd-mm-yyy HH:mm":
response.DATE_OF_DESCRIPTION = response.DATE_OF_DESCRIPTION.split(" "); // date and time are separated by an space
var date = response.DATE_OF_DESCRIPTION[0];
var time = response.DATE_OF_DESCRIPTION[1];
BTW, if you want to parse a date in a specified format, why don't you use any library for that? Many of them are almost as reliable and fast as native methods. Give them a try ;)
You could also format the date, so it fits the JS specs but, why reinvent the wheel? Libraries will do this for you and you'll get optimal cross-browser results!
I've googled "javascript date parsing library" and this is what I've found:
http://momentjs.com/ <--- I think that's what you're looking for!
NO JQUERY! I have a drop down in which the user selects a day month and year. I create the following code and pass these values into the variable using setFullYear. At times I also add days to this variable which is waht the variable ev_num is for. When I write this to the page it displays a lot of unnecessary info...
Sat Jan 01 2011 11:44:26 GMT-0500 (Eastern Standard Time)
I want it to simply read 'Jan 01 2011' or something like that. Does anyone know how I would fix this. Here is a jsfiddle of the entire page... http://jsfiddle.net/fET6v/
var myDate=new Date();
var ev_num = parseInt(document.getElementById("leave").value)
myDate.setFullYear(sel_year.value,sel_month.value,sel_day.value);
var event_value = document.getElementById("leave").value;
var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
document.write(currentMonth + " " + day + " " + year);
This will print today's date with abbreviated months. It's fully customizable.
http://jsfiddle.net/iansan5653/u7hkE/
EDIT: See this demo for the leading zero in front of the day number: http://jsfiddle.net/iansan5653/u7hkE/1/
If you don't want the time and timezone to appear, use the .toDateString method instead of the simple toString. If you want a custom format, you will need to build the string yourself, you can get the single year/month/date values with the respective methods from your Date object. There are some (googlable) libraries to do that, a single method for your case would be
function myDateString(date) {
return ["Jan","Feb","Mar", …][date.getMonth()] +
" "+("0"+date.getDate()).substr(-2) +
" "+date.getFullYear();
}
http://blog.stevenlevithan.com/archives/date-time-format