Parsing date and time from formatted date - javascript

I have a date in the following format:
Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)
Can anyone tell me how to parse the date
Wed Jul 17 2013
and time out of this without using string functions
1:00pm

One of the simplest ways is to make sure your LOCALES are set properly, which allows you to do something like this:
var myStrDate = 'Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)';
var myDate = Date.parse(myStrDate);
var myDateOnly = myDate.toLocaleDateString();
var myTimeOnly = myDate.toLocaleTimeString();
Here's a great place to start: http://www.w3schools.com/jsref/jsref_obj_date.asp

You can construct a Date object with the date string, combined with additional functions to get the required output. dayname() returns the dayname, monthname() returns the three-letter month name.
I've used console.info() for outputting results - alert() can be used as an alternative if appropriate.
function dayname(d)
{
var names = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri","Sat" ];
return names[d.getDay()];
}
function monthname(d)
{
var names = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return names[d.getMonth()];
}
// construct new date object passing date string as parameter
var d = new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)");
console.info(dayname(d) + ' ' + monthname(d) + ' ' + d.getDate() + ' ' + d.getFullYear());
For the time, this gettime() function checks the hour to output am or pm correctly, and for correct formatting-:
function gettime(d)
{
var ampm = "am";
var hour = d.getHours();
var mins = d.getMinutes();
if (hour >= 12)
{
hour = hour - 12;
ampm = "pm";
}
if (hours < 10)
hours = "0" + hours;
if (mins < 10)
mins = "0" + mins;
return hour + ":" + mins + ampm;
}
console.info(gettime(d));

var ms = Date.parse(new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)"));
var curr_date = ms.getDate();
var curr_month = ms.getMonth() + 1; //Months are zero based
var curr_year = ms.getFullYear();
var hours = ms.getHours();
var mins = ms.getMinutes();
suf = (hours >= 12)? 'pm' : 'am';
hours = hours % 12;
document.write(curr_date + "-" + curr_month + "-" + curr_year + " " + hours + ":" + min + " " + suffix);
Also try using moment.js, you can format dateTime as you wish.

Here great reference to learn date functions in javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Related

How to convert strings of the format "6 Dec, 2022 " to a date? [duplicate]

In BIRT, i have a column containing a datetime stored as a string. I need to convert these string to datetime format and put the result in another column using Javascript.
The string is the form of: for example: Fri 21 Feb 2014, 09:40 AM.
Hence this when converted to a datetime format and exported to excel, the column should be treat as a date.
Can any one of you help me to do it?
Cheers,
Other answers do not take into consideration this question is in a BIRT context.
Create a computed column in your dataset, with "Date time" as datatype
Enter as expression:
new Date(row["myDateStringField"]);
Where "myDateStringField" is your DateTime column in a String format. Then use this computed column in your report instead of the String column.
That's it!
Checkout momentjs!
You can parse your time of any format like
moment("12-25-1995", "MM-DD-YYYY");
In your case, you don't even have to specify the format. It automatically recognizes it.
And you can output ISO format or convert it to a Javascript Date object.
This is extremely easy to do with javascript. The following code will make a date in a format that Excel will recognize as a date.
http://jsfiddle.net/bbankes/d7SwQ/
var dateString = 'Fri 21 Feb 2014, 09:40 AM';
var date = new Date(dateString);
var yr = date.getFullYear();
var mo = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var hr = hours < 10 ? '0' + hours : hours;
var minutes = date.getMinutes();
var min = (minutes < 10) ? '0' + minutes : minutes;
var seconds = date.getSeconds();
var sec = (seconds < 10) ? '0' + seconds : seconds;
var newDateString = yr + '-' + mo + '-' + day;
var newTimeString = hr + ':' + min + ':' + sec;
var excelDateString = newDateString + ' ' + newTimeString;
If you just want to reformat 'Fri 21 Feb 2014, 09:04 AM' as '2014-02-21 09:04', then the following will do:
function stringToTimestamp(s) {
var t = s.match(/[\d\w]+/g);
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'};
function pad(n){return (n<10?'0':'') + +n;}
var hrs = t[4] % 12;
hrs += /pm$/i.test(t[6])? 12 : 0;
return t[3] + '-' + months[t[2].toLowerCase()] + '-' + pad(t[1]) + ' ' +
pad(hrs) + ':' + pad(t[5]);
}
console.log(stringToTimestamp('Fri 21 Feb 2014, 09:04 AM')); // 2014-02-21 09:04
use the ISO format: YYYY-MM-DDTHH:MM:SS or YYYY-MM-DD
new Date('2011-04-11T11:51:00');
or
new Date('2011-04-11');

javascript create date from string and cast back to string

I am creating a date out of strings. I want my date to have the last hour and last minute of the given day. I have a calendar that is populating an input box with a date in the form 01-02-2020 (dd-mm-yyyy).
I want to add hours minutes and seconds to the date to make it look like this string: 2020-02-01 23:59:59.
I then want to sabtract x number of days from the date I've created to get a startdate.
My issue is that my date values are being somehow converted when I use the date functions. What I am doing is:
enddate = new Date(enddate);
enddate = enddate.setHours(23,59,59);
var startdate = new Date();
startdate.setDate( enddate.getDate() - 5);
I then want to concatenate my two dates to a string. Like ?startdate=2020-01-26 00:00:00&enddate=2020-02-01 23:59:59. Where the startdate has hours, minutes and seconds in the form 00:00:00 This string is what I ultimately want and it doesn't matter how I get to this start and enddate value. The steps above are just what I've tried. And actually the format of my dates in the the final string doesn't matter as long as it is something that sql can recognize and treat as a date.
How can I accomplish this?
Here is my full code:
enddate holds a date value in this form: 01-02-2020 (day month year european style)
datesplit = enddate.split("-");
enddate = new Date(datesplit[2],datesplit[0],datesplit[1]); //mm-dd-yyyy for US format
enddate.setHours(23);
enddate.setMinutes(59);
var startdate = new Date(enddate);
startdate.setDate(startdate.getDate() - daysback);
startdate.setHours(00);
startdate.setMinutes(00);
console.log("startdate and enddate: " + startdate + " - " + enddate)
//startdate and enddate: Tue Jan 28 2020 00:00:00 GMT-0500 (Eastern Standard Time) - Sun Feb 02 2020 23:59:00 GMT-0500 (Eastern Standard Time)
console.log("startdate and enddate date string: " + startdate.toISOString() + " - " + enddate.toISOString());
//startdate and enddate date string: 2020-01-27T05:00:00.000Z - 2020-02-03T04:59:00.000Z
Why the added time in the last console log value when the date is cast to ISO?? That last format is what I want, but value is different.
var st = "01-02-2020";
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
enddate = new Date(dt);
enddate.setHours(23,59,59);
var startdate = new Date(dt);
startdate.setHours(00,00,00);
startdate.setDate( startdate.getDate() - 5);
function js_yyyy_mm_dd_hh_mm_ss (mydate) {
now = new Date();
year = "" + mydate.getFullYear();
month = "" + (mydate.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
day = "" + mydate.getDate(); if (day.length == 1) { day = "0" + day; }
hour = "" + mydate.getHours(); if (hour.length == 1) { hour = "0" + hour; }
minute = "" + mydate.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
second = "" + mydate.getSeconds(); if (second.length == 1) { second = "0" + second; }
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
var query = '?startdate='+js_yyyy_mm_dd_hh_mm_ss(startdate)+'&enddate='+js_yyyy_mm_dd_hh_mm_ss(enddate);
alert(query);
Well the problem basically was that you assign the same variable to different uses. I separate it (by adding 1 to the second one) and that solve it:
const enddate = '02-01-2020';
const daysback = 5;
datesplit = enddate.split("-");
enddate1 = new Date(datesplit[2],datesplit[0],datesplit[1]); //mm-dd-yyyy for US format
enddate1.setHours(23);
enddate1.setMinutes(59);
var startdate = new Date(enddate1);
startdate.setDate(startdate.getDate() - daysback);
startdate.setHours(00);
startdate.setMinutes(00);
console.log("startdate and enddate: " + startdate + " - " + enddate)
//startdate and enddate: Tue Jan 28 2020 00:00:00 GMT-0500 (Eastern Standard Time) - Sun Feb 02 2020 23:59:00 GMT-0500 (Eastern Standard Time)
console.log("startdate and enddate date string: " + startdate.toISOString() + " - " + enddate1.toISOString());
//startdate and enddate date string: 2020-01-27T05:00:00.000Z - 2020-02-03T04:59:00.000Z

How to change date format and add a 0 in front [duplicate]

This question already has answers here:
Javascript add leading zeroes to date
(31 answers)
Closed 7 years ago.
I have this code:
CODE JS:
var completeD = start.format("YYYY/MM/DD HH:mm");
var dt = new Date(completeD);
console.log(dt) //here it's display Tue Feb 09 2016 02:00:00 GMT+0200 (EET)
console.log(dt.getHours() + ":" + dt.getMinutes()); //the input value is 2:0
The input value is 2:0 and should be 02:00
How can I add a 0 in front ...?if it's neccesarry.
Thanks in advance!
simple way is to write a function to correct the string:
function normalize(n) {
if (n < 10) {
n = "0" + n;
}
return n;
}
var completeD = start.format("YYYY/MM/DD HH:mm");
var dt = new Date(completeD);
console.log(normalize(dt.getHours()) + ":" + normalize(dt.getMinutes()));
use a pad function
function pad(var value) {
if(value < 10) {
return '0' + value;
} else {
return value;
}
}
now you can use it
console.log( pad( dt.getHours() ) + ":" + pad ( dt.getMinutes()) ); // outputs 02:00
You can try this : (click on run code snippet to see result in console)
var dt = new Date();
console.log(dt) //here it's display Tue Feb 09 2016 02:00:00 GMT+0200 (EET)
var hours = dt.getHours();
var minute = dt.getMinutes();
if(hours.toString().length == 1 ) hours = "0"+hours;
if(minute.toString().length == 1 ) minute = "0"+minute;
console.log(hours + ":" + minute); //the input value is 2:0
alert(hours + ":" + minute) ;
You can use regular expression for it:
var dt = 'Tue Feb 09 2016 02:00:00 GMT+0530 (India Standard Time)';//new Date();
document.querySelector('pre').innerHTML = dt.match(/(\d\d:\d\d)/g)[0];
<pre></pre>

how to convert date object of js to time in h:i A (7:30 A.M) format

I have a javascript object of date and its value is:
Thu Dec 18 2014 07:29:44 GMT+0500 (PKT)
Now I want to get the time from above data object in following format:
7:29 A.M
How can I do that using javascript code.
Please Help!!
You can do a little string addition by doing the following:
var result = "";
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var amORpm = hours > 12 ? "P.M" : "A.M";
if(hours > 12) hours -= 12;
result = hours + ":" + minutes + " " + amORpm;
console.log(result); // Will get you your desired format

convert UTC to mysql dateTime javascript

I'm having trouble converting an example string: 'Sun Feb 02 19:12:44 +0000 2014'
to mysql dateTime format in javascript
any help would be greatly appreciated
You can convert date time to mysql format using this code:
var myDate = new Date('Sun Feb 02 19:12:44 +0000 2014'),
year = myDate.getFullYear(),
month = ('0' + (myDate.getMonth() + 1)).slice(-2),
day = ('0' + myDate.getDate()).slice(-2),
hour = ('0' + myDate.getHours()).slice(-2),
minute = ('0' + myDate.getMinutes()).slice(-2),
seconds = ('0' + myDate.getSeconds()).slice(-2),
mysqlDateTime = [year, month, day].join('-') + ' ' + [hour, minute, seconds].join(':');
However I would suggest to send it to backend as timestamp (+(new Date('Sun Feb 02 19:12:44 +0000 2014'))) or formatted string (myDate.toISOString()) and proceed with conversion there.
try this:
var d = new Date('Sun Feb 02 19:12:44 +0000 2014');
var month = d.getMonth();
if(month < 10)
month = "0" + month;
var day = d.getDate();
if(day < 10)
day = "0" + day;
hour = d.getHours();
if(hour < 10)
hour = "0" + hour;
minute = d.getMinutes();
if(minute < 10)
minute = "0" + minute;
seconds = d.getSeconds();
if(seconds < 10)
seconds = "0" + seconds;
var mysqlDate = d.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds;

Categories

Resources