Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK Date How to get next monday

Status
Not open for further replies.

umi6kg

MIS
Jan 6, 2003
3
JP
I'm very new to awk, Linux, UNIX... please help.

I'd like to know how to get nextmonday and next sunday
without using date option, 'next monday' or '3 sunday'.

I wrote a script which is to access UNIX(set sqlplus command) and run sql, create csv file. To create sql,
next monday and next sunday is needed.
It's OK to run from Linux, but I want to run from UNIX.
Is there same date option?(we failed to set up date library. compile error?)


GNU?
{"date --date 'next monday' +'%Y%m%d'" | getline nextmonday}
{"date --date '3 sunday' +'%Y%m%d'" | getline nextsunday}


cat test.awk

BEGIN {

{"date +'%Y%m%d'" | getline today}
{"date +'%w'" | getline a}

{"date +'%Y'" | getline year}
{"date +'%m'" | getline month}
{"date +'%d'" | getline day}

{"date +'%s'" | getline sec}

# Sun 0
# Mon 1
# Tue 2
# Wed 3
# Thu 4
# Fri 5
# Sat 6

if (a==0) plus=1
if (a==1) plus=7
if (a==2) plus=6
if (a==3) plus=5
if (a==4) plus=4
if (a==5) plus=3
if (a==6) plus=2

nextmonday = today + 86400 * plus
nextsunday = nextmonday + 86400 * 13

test = nextmonday + sec

{print "today: " today}
{print "day : " a}
{print "plus: " plus}
{print "NM: " nextmonday}
{print "NS: " nextsunday}

{print "sec :" sec}
{print "test:" test}
}

awk -f test.awk

today: 20030115
day : 3
plus: 5
NM: 20462115
NS: 21585315
sec :1042592609
test:1063054724


Thanks,
Suzy
 
Suzy:

If you are using GNU tools such as gawk and GNU date you can solve this with manipulating the number of seconds since the EPOCH. Since most other *nix do not natively support the GNU tools, check out this Tek-tips thread for other methods for doing date arithmetic:

thread822-445663

Regards,

Ed

#!/bin/bash

# no error checking, $1 is whatever the next day you're looking for
# $1 should be between 0 and 6.
# 1 for monday, 2 for tuesday, etc.
a=$(date '+%w') # todays date 0 to 6

if [ $a -lt $1 ]
then # needs more testing
# today's monday, what's the next thursday
dd=$(($1-$a))
else
# today's thursday, what's the next monday
dd=$((6-$a+$1+1))
fi

# determine the number of days from the system date
# systime() returns the number of seconds from EPOCH
# strftime() formats date taking argument of number of
# seconds from the EPOCH.
echo ""|gawk -v days=$dd ' {
target_date = systime() + (86400 * days)
datestring = strftime("%c", target_date)
printf "%s\n", datestring } '
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top