I have a 5 digit number stored in a variable. The next step is to convert the number to a date. for example
var x = 20151506;
The above number has to be converted to:
Thu June 15 2015 06:35:50
Please note that you must first specify the time in your original date value for it to be formatted and included correctly in your output. Thus the following will not provide the time element as you're looking for.
Referencing this SO answer:
function parse(str) {
var y = str.substr(0,4),
m = str.substr(6,2) - 1,
d = str.substr(4,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
Usage:
parse('20151506');
Output:
Mon Jun 15 2015 00:00:00 GMT-0500 (Central Daylight Time)
or in your case
parse(x.toString());
Output:
Mon Jun 15 2015 00:00:00 GMT-0500 (Central Daylight Time)
Code snippet provided below:
var x = 20151506;
function parse(str) {
var y = str.substr(0,4),
m = str.substr(6,2) - 1,
d = str.substr(4,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
//document.write (parse('20151506'));
document.write (parse(x.toString()));
To convert that "number" in to a Date you'll have to split it into the relevant year month day (hours, minutes and seconds appear to be missing).
var x = 20151506;
var month = x % 100;
var day = Math.floor(x % 10000 / 100);
var year = Math.floor(x / 10000);
var date = new Date(year, month - 1, day)
This will give you the value of date in whateve your local timezone is - Mon Jun 15 2015 00:00:00 GMT+0100 (GMT Daylight Time).
Not sure where you get the your time part from?
Related
Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)
And from the time picker plugin getting the time 1:10am or 2:30pm in this format.
I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)
I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)
Seems like you need to parse it on your own:
function parseDaytime(time) {
let [hours, minutes] = time.substr(0, time.length -2).split(":").map(Number);
if (time.includes("pm") && hours !== 12) hours += 12;
return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}
To add it to a date:
new Date(
+new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
+parseDaytime("1:20pm")
);
Here is a simple function to do what your after.
It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.
The example below takes the current datetime, and sets 1:10am & 2:40pm..
function setHours(dt, h) {
var s = /(\d+):(\d+)(.+)/.exec(h);
dt.setHours(s[3] === "pm" ?
12 + parseInt(s[1], 10) :
parseInt(s[1], 10));
dt.setMinutes(parseInt(s[2],10));
}
var d = new Date();
console.log(d);
setHours(d, "1:10am");
console.log(d);
setHours(d, "2:40pm");
console.log(d);
You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:
var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)
(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)
I have a calender and has following two scenarios:
case - 1
current_month = 8 (aug)
end_month = 10 (oct)
current_year = 2017
end_year = 2017
case - 2
current_month = 8 (aug)
end_month = 2 (feb)
current_year = 2017
end_year = 2018
When I click next month it should move only until "end_month". What should be the condition to satisfy both the cases:
if(condition)
alert("Move to next month");
else
alert("condition fail");
I have tried comparing start and end date objects, But I'm able to move one more month extra, which should not happen.
I have used the following conditions:
cal_date = Tue Aug 01 2017 23:58:33 GMT+0530 (India Standard Time)
$scope.edate = Wed Nov 15 2017 00:00:00 GMT+0530 (India Standard Time)
if (cal_date.getMonth() > $scope.edate.getMonth() + 1 || cal_date.getMonth() == $scope.edate.getMonth() || $scope.edate.getFullYear() <= new Date().getFullYear())
if (cal_date.getMonth() > $scope.edate.getMonth() || cal_date.getMonth() == $scope.edate.getMonth())
if (cal_date.getTime() < new Date(new Date($scope.edate) - 1)) {
if (cal_date < $scope.edate) {
Personally I would create Date objects:
var current = new Date(year,month)
var end = new Date(year,month)
and then test:
if ( current<end )
That would probably be the simplest approach.
I have following time "Mon Jun 22 03:45:24 PDT 2015" how can I get Meridian using Javascript.
I was doing this:
d= Mon Jun 22 03:45:24 PDT 2015;
var hours = d.getHours();
var meridiem = "AM";
if (d.getHours() > 12) {
hours = d.getHours() % 12;
if (hours == 2) {
hours = 12;
}
meridiem = "PM";
}
But its not working in IE 8.
you define
d= Mon Jun 22 03:45:24 PDT 2015;
actually it is nothing in javascript
some browser more intelligent some not, it's up to the browser behaviour
you have to tell javascript like that
function getCurrentTime() {
var currentTime;
// here we can give our date
var currentDate = new Date("Mon Jun 22 03:45:24 PDT 2015");
// OR we can define like that also for current date
// var currentDate = new Date();
var hour = currentDate.getHours();
var meridiem = hour >= 12 ? "PM" : "AM";
currentTime = ((hour + 11) % 12 + 1) + ":" + currentDate.getMinutes() + meridiem;
return currentTime;
}
We can get time in 12 hour format, including the meridian by using the Date.prototype.toLocaleTimeString() method with a US English argument which returns the time in AM/PM. Without the argument 'en-US' date will return the format it deems appropriate for your timezone.
From there we can utilise the slice method to get the last two characters of the timestamp using a negative index:
var d = new Date("Mon Jun 22 03:45:24 PDT 2015")
// US English uses 12-hour time with AM/PM
var timestamp = d.toLocaleTimeString('en-US');
// timestamp → "03:45:24 AM"
var meridian = timestamp.slice(-2);
// meridian → "AM"
One liner for brevity:
var meridian = new Date("Mon Jun 22 03:45:24 PDT 2015").toLocaleTimeString().slice(-2);
According to the documentation for JavaScript Date object here, there is no method for directly getting 12-hour hours and therefore no method for getting am/pm directly from the Date object.
You can get hours (24-hour format) which you can use to get 12-hour hours and am/pm. (You've already done it but I don't understand what you're trying to do in your code.)
This would be one way to do this.
This code is inspired by #tinka.
var d = new Date("Mon Jun 22 03:45:24 PDT 2015");
var h = (d.getHours() + 11) % 12 + 1; //Courtesy #tinka
var m = h > 12 ? 'pm' : 'am';
And you can always add methods to Date.prototype if you're gonna be using them repeatedly.
Date.prototype.getHours12 = function() {
return (this.getHours() + 11) % 12 + 1; // edited.
}
Date.prototype.getMeridiem = function() {
return this.getHours() > 12 ? 'pm' : 'am';
}
It should work on all platforms.
With Date object:
getMeridiem(date: Date) {
return date.toLocaleTimeString().split(' ')[1];
}
I'm getting a strange result:
var date = new Date();
var year = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;
console.log(new Date(Date.UTC(year, month)));
var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;
console.log(new Date(utcYear, utcMonth));
With the particular date I'm using (any date will do), Date.UTC gives me:
Sun May 31 2015 19:00:00 GMT-0500 (Central Daylight Time)
The getUTC... aproach gives me:
Mon Jun 01 2015 00:00:00 GMT-0500 (Central Daylight Time)
Am I mis-using Date.UTC or am I missing something?
Thanks
You are creating a Date using UTC time, but then you are displaying it in local time, that's why it's a few hours behind. Use Date.prototype.toUTCString() to see the UTC time
var date = new Date();
var year = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;
// It's a UTC date, display it as UTC, not local time
console.log(new Date(Date.UTC(year, month)).toUTCString());
var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;
// Created using local time, you can just use the normal toString()
console.log(new Date(utcYear, utcMonth));
This code is to get the first day of the next month (something that reoccurs monthly and can't start until next month).
Then you're looking for
var today = new Date(); // now
var utcYear = today.getUTCMonth() < 11 ? today.getUTCFullYear() : today.getUTCFullYear() + 1;
var utcMonth = today.getUTCMonth() < 11 ? today.getUTCMonth() + 1 : 0;
var date = new Date(Date.UTC(utcYear, utcMonth)); // next UTC month
console.log(date.toString()); // Mon Jun 01 2015 02:00:00 GMT+0200
// or, in your timezone: Sun May 31 2015 19:00:00 GMT-0500 (same moment)
console.log(date.toUTCString()); // Mon, 01 Jun 2015 00:00:00 GMT
Btw, the Date methods does take too large values into accout (and carry-over them automatically), so you just would need to do
var today = new Date(); // now
var date = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth()+1)); // next UTC month
I have a variable that contains JSON data with thousands of rows. Some of the variables are dates in the following format Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time). I need to convert all of these variables into a more usable date format such as `mm/dd/yyyy'.
Any suggestions on how to accomplish this?
{
"request": [
{ "startdate":"Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)" ,
"status":"in progress" }, ...
]}
Thanks in advance!
You can pass the date string as an argument when instantiating the Date class. Javascript doesn't have a good date formatter, but you can easily roll your own. For instance:
function parseDate(date) {
var d = new Date(date);
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
if(month < 10) month = '0' + month;
if(day < 10) day = '0' + day;
return month + '/' + day + '/' + year;
}
parseDate('Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)');
// returns "06/27/2008"
Try the following:
var json = {
"request": [
{ "startdate":"Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)" ,
"status":"in progress" }
]};
var date = new Date(json.request[0].startdate);
var formatDate = function(date) {
var mm = date.getMonth()+1;
mm = mm > 10 ? mm : "0"+mm;
var dd = date.getDate();
dd = dd > 10 ? dd : "0"+dd;
var yy = date.getFullYear();
return mm+"/"+dd+"/"+yy;
}
var formattedDate = formatDate(date);
Always best to convert a string to a date object is to manually parse it unless you have a very controlled environment. The following should do the job:
// Use date string to create a UTC time to pass to Date constructor
// Expected format is day mon year hh:mm:ss GMToffset (timezone name)
// e.g. Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)
function parseDate(s) {
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
var s = s.split(/[ :]/g);
var offset = s[7];
// Deal with offset
var sign = offset.indexOf('-') >= 0? -1 : 1;
var len = offset.length;
var offMins = sign * offset.substring(len-4, len-2) * 60 + sign * offset.substring(len-2, len);
var mins = s[4] - offMins;
return new Date(Date.UTC(s[3], months[s[1].toLowerCase()], s[2], s[4], mins, s[6]));
}
var s = 'Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)';
alert(parseDate(s)); //Fri 27 Jun 2008 17:00:00 GMT+1000
You can then format the date however you want:
function formatDateUS(d) {
function z(n){return (n<10? '0':'') + n}
return z(d.getMonth()+1) + '/' + z(d.getDate()) + '/' + d.getFullYear();
}
formatDateUS(parseDate(s)); // 06/27/2008