Breaking down a date into segments [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Simplest way to parse a Date in Javascript
I understand how do get the data and break it down into it's segments, i.e.
alert( ( new Date ).getDate() );
and
alert( ( new Date ).getFullYear() );
alert( ( new Date ).getFullMonth() );
etc etc.
But how do I do the same but use a date from a html textbox? instead of reading new Date?
The date in the HTML box would be formated as follows
31/10/2012

You could try:
var datearray = input.value.split("/");
var date = new Date(datearray[2],datearray[1] - 1,datearray[0])

If your textbox has proper string format for a date object you can use:
var aDate = new Date($("textbox").val());
However, if you dont write it in the text box exactly as you would in a string passing to the object, you'll get null for your variable.
FYI, I made a plugin that "extends" the Date object pretty nicely and has preformatted date/times that include things like a basic SQL datetime format.
Just go to this jsFiddle, Copy the code between Begin Plugin and End Plugin into a js file and link it in your header after your jQuery.
The use is as simple as above example:
var aDate = new DateTime($("textbox").val());
And to get a specific format from that you do:
var sqlDate = aDate.formats.compound.mySQL;

Related

Convert JSON /Date(1238626800000)/ to Unix Timestamp [duplicate]

This question already has answers here:
How to parse JSON to receive a Date object in JavaScript?
(17 answers)
Closed 5 years ago.
In my code I get JSON response as /Date(1238626800000)/.
I want to convert this object to Unix Timestamp. So I would like to know that whether is there any default javascript or jquery method which can convert it to Unix Timestamp ?
So My Input Date is: /Date(1238626800000)/ and
Output I want is: 1238626800000
I can do it with RegEx but this is last option if no default method available
No need to use regex here. Just slice out the timestamp:
if (value.startsWith("/Date(") && value.endsWith(")/"))
return new Date(Number(value.slice(6, -2)));
like this:
var input = '/Date(1238626800000)/';
var re = /Date\(([0-9]*)\)/;
var ret = re.exec(a);
if(ret) {
input = ret[1];
}

How to check date validation in regex using js? [duplicate]

This question already has answers here:
Javascript: how to validate dates in format MM-DD-YYYY?
(21 answers)
Closed 6 years ago.
I am trying to validate date in js ("yyyy/mm/dd") format. After googling I found other date format checked but I can't get in this format.
Any one plz can help me out.
Here is my code.
function dateChecker()
{
var date1, string, re;
re = new RegExp("\d{4}/\d{1,2}/\{1,2}");
date1 = document.getElementById("visitDate").value;
if(date1.length == 0)
{
document.getElementById("showError").innerHTML = "Plz Insert Date";
document.getElementById("showError").style.color = "red";
}
else if(date1.match(re))
{
document.getElementById("showError").innerHTML = "Ok";
document.getElementById("showError").style.color = "red";
}
else
{
document.getElementById("showError").innerHTML = "It is not a date";
document.getElementById("showError").style.color = "red";
}
}
Try this:
var date = "2017/01/13";
var regex = /^[0-9]{4}[\/][0-9]{2}[\/][0-9]{2}$/g;
console.log(regex.test(date)); // true
console.log(regex.test("13/01/2017")); //false
console.log(regex.test("2017-01-13")); // false
If you use new RegExp then you must call compile on the resulting regular expression object.
re = new RegExp("\d{4}/\d{1,2}/\d{1,2}");
re.compile();
Alternatively you could write the regex this way which does not require compile to be called.
re = /\d{4}\/\d{1,2}\/\d{1,2}/;
EDIT
Note that the above regex is not correct (ie it can approve invalid dates). I guess the brief answer is, don't use regex to validate date times. Use some datetime library like momentjs or datejs. There is too much logic. For instance, how do you handle leap years, different months having different number of possible days, etc. Its just a pain. Use a library that can parse it, if it cant be parsed, its not a date time. Trust the library.
However you could get closer with something like this
re = /^\d{4}\/(10|11|12|\d)\/((1|2)?\d|30|31)$/;
Also if you want to get comfortable with regex, download Expresso

Show yyyyww (yearweek) in Google Scripts / Javascript (Sunday-Monday)

I'm really struggling to do a clean, efficient way of showing yearweek for Sunday to Monday
e.g.:
201624
201625
201626
201627
201628
Is there an efficient way to do so in Google Scripts or Javascript without using a library?
Thanks!
Found a solution! :
var yearMonth = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "yyyyww")).toFixed(0);
It was provided by user: Balu Ertl at Get week of year in JavaScript like in PHP
I would use Moment.js. Documentation for the use can be found here for the format you are looking for http://momentjs.com/docs/#/displaying/.
To have it work with google script you will need to first add it to the libraries using MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48, then you need to load it in using something like var moment = Moment.load().
From here you can get the month and year already formatted into your requested format.
var date = getDate();
var wwyy = moment(date).format('wo, YY');
My appologies, my format wasn't exactly as you wanted it to be. To answer in the format you are looking for:
var date = new Date();
var yyyyww = moment(date).format('YYYY ww');

Get time difference between two date strings

I want to develop a JavaScript function to calculate the activity of users based on the date in the server where the data is stored. The problem is that the date is a string like this:
2013-08-11T20:17:08.468Z
How can I compare two string like this to calculate minor and major time as in the example?
If you want to compare two dates just use this :
var dateA = '2013-08-11T20:17:08.468Z';
var parsedDateA = new Date(dateA).getTime();
var dateB = '2013-06-06T17:33:08.468Z';
var parsedDateB = new Date(dateB).getTime();
if(parsedDateA > parsedDateB) {
// do something
}
Assuming you need to do the comparisons client-side, the best way is to load the dates into Date objects using Date.parse. Then compare them using the functions provided for Date, such as getTime.
Try parse method:
var s = "2013-08-11T20:17:08.468Z";
var d = Date.parse(s);
As I have understood you in the right way, there is a good answer to your question here.
You can also look at this very good Library (DateJS).
If your problem was converting from the Date-String to js-Date look at this Page.

jQuery Slideshow from XML with date parameters

So I have been tasked with creating a jQuery slideshow from an XML file with a timing mechanism to change the images based on date. I have the slideshow working from the XML, but I am struggling with adding the date feature. I would like to be able to "turn on" and "turn off" images based on the onDate and offDate. I understand Javascript is not the best way to show things based on date, but there are limits within the current site structure that prevent server side timing. So I would like to have the ability to load up say 10 images, and then only show three based on what today's date is, and what the onDate/offDate are.
This is the logic I was thinking.... If today is < onDate .hide or if today is > offDate .hide else .show
Where I am struggling
The correct way to enter the date in the XML file.
Parsing the date from XML into something that Javascript and in turn jQuery can use to compare today's date with the date in XML and show the image accordingly.
Once the date has been established figuring out a way to show or hide the specific image based on date.
Any help would be greatly appreciated.
XML
<eq-banner>
<id>1</id>
<url>linktopage.html</url>
<img>image.jpg</img>
<dept>equipment</dept>
<onDate>12/01/2010</onDate>
<offDate>12/31/2010</offDate>
<copy>FREE Stuff</copy>
</eq-banner>
jQuery
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "rotationData.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(equipment) {
$(equipment).find('eq-banner').each(function() {
var id = $(this).attr('id');
var dept = $(this).find('dept').text();
var url = $(this).find('url').text();
var img = $(this).find('img').text();
$('<div class="'+dept+'"</div>').html('<img src="images/'+img+'" /><br />').appendTo('#apparel')
$("#equipment").cycle({
fx:"fade",
speed:100,
timeout:5000
});;
});
}
</script>
HTML
<div id="equipment">
</div>
If you trust the data quality of the XML source, specifically that the dates are all well-formed as in your sample, it's pretty easy to turn that into a JavaScript "Date" object:
var str = "12/31/2010";
var pieces = str.split('/');
var date = new Date(~~str[2], ~~str[0] - 1, ~~str[1]);
(The ~~ trick converts the strings to numbers; do that however you prefer.) Also months are numbered from zero, and hence the subtraction.
Comparing dates works perfectly well in JavaScript, or you can call the ".getTime()" method on a date to explicitly get a "milliseconds since the epoch" value to compare instead.
As to how you'd show/hide the images, I'd be inclined to conditionally add a class to elements to be hidden (or shown; whichever makes the most sense).
XML doesn't have a "correct" way of handling dates, and JavaScript can parse just about anything. However, the most JS-friendly format would be something like "October 20, 2011" with the time optionally added in "12:34:56" format. A string like that can be fed directly to the new Date() constructor and be parsed correctly regardless of location.
datestr = "October 20, 2011";
date = new Date(datestr);
To compare Date objects, just use < or > -- however, a JS Date object contains a time element which will also be compared. So if you create a new Date object for the present with var now = new Date(); and compare it to var dat = new Date("string with today's date"); you'll find that dat is less than now because dat has time 00:00:00 while now has the present time. If this is a problem, you'll have to explicitly compare Date.getDate(), Date.getMonth() and Date.getFullYear() all at once. ( http://www.w3schools.com/jsref/jsref_obj_date.asp )

Categories